Skip to main content
Glama
ahnmichael

GitLab Forum MCP

by ahnmichael

Discourse Search

discourse_search

Search GitLab community forum content to find discussions and solutions for troubleshooting CI/CD issues and GitLab features.

Instructions

Search site content.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query
with_privateNo
max_resultsNo

Implementation Reference

  • The handler function that executes the discourse_search tool. It performs an API search on the Discourse site using the provided query, processes the results (topics and posts), formats a text response with links, and includes a JSON summary of results.
    async (args, _extra: any) => {
      const { query, with_private = false, max_results = 10 } = args;
      const { base, client } = ctx.siteState.ensureSelectedSite();
      const q = new URLSearchParams();
      q.set("expanded", "true");
      const fullQuery = ctx.defaultSearchPrefix ? `${ctx.defaultSearchPrefix} ${query}` : query;
      q.set("q", fullQuery);
    
      // Debug logging
      ctx.logger?.debug(`Search query: "${query}"`);
      ctx.logger?.debug(`Full query with prefix: "${fullQuery}"`);
      ctx.logger?.debug(`Search URL: ${base}/search.json?${q.toString()}`);
    
      try {
        const data = (await client.get(`/search.json?${q.toString()}`)) as any;
    
        // Debug the response structure
        ctx.logger?.debug(`Search response keys: ${Object.keys(data || {}).join(', ')}`);
        ctx.logger?.debug(`Topics found: ${data?.topics?.length || 0}`);
        ctx.logger?.debug(`Posts found: ${data?.posts?.length || 0}`);
    
        const topics: any[] = data?.topics || [];
        const posts: any[] = data?.posts || [];
    
        // If no topics but we have posts, we can extract topic info from posts
        let items = topics.map((t) => ({
          type: "topic" as const,
          id: t.id,
          title: t.title || t.fancy_title || `Topic ${t.id}`,
          slug: t.slug || String(t.id),
        })) as Array<{ type: "topic"; id: number; title: string; slug: string }>;
    
        // If we don't have enough topics, supplement with unique topics from posts
        if (items.length < max_results && posts.length > 0) {
          const existingTopicIds = new Set(items.map(t => t.id));
          const postTopics = posts
            .filter(p => p.topic_id && !existingTopicIds.has(p.topic_id))
            .map(p => ({
              type: "topic" as const,
              id: p.topic_id,
              title: `Post topic ${p.topic_id}`, // We don't have the topic title from post
              slug: String(p.topic_id),
            }));
    
          // Add unique post topics up to our limit
          const seenIds = new Set();
          for (const pt of postTopics) {
            if (items.length >= max_results) break;
            if (!seenIds.has(pt.id)) {
              seenIds.add(pt.id);
              items.push(pt);
            }
          }
        }
    
        items = items.slice(0, max_results);
    
        const lines: string[] = [];
        if (items.length === 0) {
          lines.push(`No results found for "${query}"`);
          // Add some debug info about what we got
          if (posts.length > 0) {
            lines.push(`Found ${posts.length} posts but no direct topics`);
          }
        } else {
          lines.push(`Top results for "${query}":`);
          let idx = 1;
          for (const it of items) {
            const url = `${base}/t/${it.slug}/${it.id}`;
            lines.push(`${idx}. ${it.title} – ${url}`);
            idx++;
          }
        }
    
        const jsonFooter = {
          results: items.map((it) => ({ id: it.id, url: `${base}/t/${it.slug}/${it.id}`, title: it.title })),
        };
        const text = lines.join("\n") + "\n\n```json\n" + JSON.stringify(jsonFooter) + "\n```\n";
        return { content: [{ type: "text", text }] };
      } catch (e: any) {
        ctx.logger?.error(`Search failed: ${e?.message || String(e)}`);
        return { content: [{ type: "text", text: `Search failed: ${e?.message || String(e)}` }], isError: true };
      }
    }
  • Input schema for the discourse_search tool using Zod, validating query (required string), optional with_private boolean, and optional max_results (1-50).
    const schema = z.object({
      query: z.string().min(1).describe("Search query"),
      with_private: z.boolean().optional(),
      max_results: z.number().int().min(1).max(50).optional(),
    });
  • Registers the discourse_search tool with the MCP server inside the registerSearch function, specifying title, description, input schema, and handler.
    server.registerTool(
      "discourse_search",
      {
        title: "Discourse Search",
        description: "Search site content.",
        inputSchema: schema.shape,
      },
      async (args, _extra: any) => {
        const { query, with_private = false, max_results = 10 } = args;
        const { base, client } = ctx.siteState.ensureSelectedSite();
        const q = new URLSearchParams();
        q.set("expanded", "true");
        const fullQuery = ctx.defaultSearchPrefix ? `${ctx.defaultSearchPrefix} ${query}` : query;
        q.set("q", fullQuery);
    
        // Debug logging
        ctx.logger?.debug(`Search query: "${query}"`);
        ctx.logger?.debug(`Full query with prefix: "${fullQuery}"`);
        ctx.logger?.debug(`Search URL: ${base}/search.json?${q.toString()}`);
    
        try {
          const data = (await client.get(`/search.json?${q.toString()}`)) as any;
    
          // Debug the response structure
          ctx.logger?.debug(`Search response keys: ${Object.keys(data || {}).join(', ')}`);
          ctx.logger?.debug(`Topics found: ${data?.topics?.length || 0}`);
          ctx.logger?.debug(`Posts found: ${data?.posts?.length || 0}`);
    
          const topics: any[] = data?.topics || [];
          const posts: any[] = data?.posts || [];
    
          // If no topics but we have posts, we can extract topic info from posts
          let items = topics.map((t) => ({
            type: "topic" as const,
            id: t.id,
            title: t.title || t.fancy_title || `Topic ${t.id}`,
            slug: t.slug || String(t.id),
          })) as Array<{ type: "topic"; id: number; title: string; slug: string }>;
    
          // If we don't have enough topics, supplement with unique topics from posts
          if (items.length < max_results && posts.length > 0) {
            const existingTopicIds = new Set(items.map(t => t.id));
            const postTopics = posts
              .filter(p => p.topic_id && !existingTopicIds.has(p.topic_id))
              .map(p => ({
                type: "topic" as const,
                id: p.topic_id,
                title: `Post topic ${p.topic_id}`, // We don't have the topic title from post
                slug: String(p.topic_id),
              }));
    
            // Add unique post topics up to our limit
            const seenIds = new Set();
            for (const pt of postTopics) {
              if (items.length >= max_results) break;
              if (!seenIds.has(pt.id)) {
                seenIds.add(pt.id);
                items.push(pt);
              }
            }
          }
    
          items = items.slice(0, max_results);
    
          const lines: string[] = [];
          if (items.length === 0) {
            lines.push(`No results found for "${query}"`);
            // Add some debug info about what we got
            if (posts.length > 0) {
              lines.push(`Found ${posts.length} posts but no direct topics`);
            }
          } else {
            lines.push(`Top results for "${query}":`);
            let idx = 1;
            for (const it of items) {
              const url = `${base}/t/${it.slug}/${it.id}`;
              lines.push(`${idx}. ${it.title} – ${url}`);
              idx++;
            }
          }
    
          const jsonFooter = {
            results: items.map((it) => ({ id: it.id, url: `${base}/t/${it.slug}/${it.id}`, title: it.title })),
          };
          const text = lines.join("\n") + "\n\n```json\n" + JSON.stringify(jsonFooter) + "\n```\n";
          return { content: [{ type: "text", text }] };
        } catch (e: any) {
          ctx.logger?.error(`Search failed: ${e?.message || String(e)}`);
          return { content: [{ type: "text", text: `Search failed: ${e?.message || String(e)}` }], isError: true };
        }
      }
    );
  • Top-level call to registerSearch during the registration of all tools, effectively registering the discourse_search tool.
    registerSearch(server, ctx, { allowWrites: false });

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed2 schema fields changedv1.0.0
    • addedInput schema / $schema
      Added value: +"http://json-schema.org/draft-07/schema#"
    • addedInput schema / additionalProperties
      Added value: +false
  2. First observed

TDQS

C2.6/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden. It only states the action ('search') without disclosing behavioral traits such as authentication requirements, rate limits, whether results are paginated, or what the output format looks like. For a search tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise with just three words, front-loaded and zero waste. It efficiently conveys the core purpose without unnecessary elaboration, making it easy to scan and understand quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (search functionality with 3 parameters), no annotations, no output schema, and low schema description coverage, the description is incomplete. It doesn't cover key aspects like result format, error handling, or behavioral constraints, leaving the agent with insufficient information to use the tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 33% (only 'query' has a description), with 3 parameters total. The description adds no meaning beyond the schema—it doesn't explain what 'with_private' does (e.g., include private content) or how 'max_results' affects pagination. It fails to compensate for the low coverage, leaving most parameters undocumented in both schema and description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Search site content' clearly indicates the verb 'search' and resource 'site content', but it's vague about what 'site content' encompasses (topics, posts, users, etc.) and doesn't distinguish from siblings like discourse_filter_topics or discourse_select_site. It states what the tool does but lacks specificity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives is provided. It doesn't mention when to prefer this over siblings like discourse_filter_topics for filtering or discourse_select_site for site selection, nor does it specify any prerequisites or exclusions. The description offers no usage context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.