Skip to main content
Glama
ahnmichael

GitLab Forum MCP

by ahnmichael

Read Topic

discourse_read_topic

Retrieve topic metadata and initial posts from GitLab's community forum to analyze discussions for troubleshooting CI/CD issues and GitLab features.

Instructions

Read a topic metadata and first N posts.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
topic_idYes
post_limitNo
start_post_numberNoStart from this post number (1-based)

Implementation Reference

  • The core handler function that implements the tool logic: fetches topic metadata and up to post_limit posts from Discourse API using HTTP client, handles pagination with 'near' parameter, extracts raw content, formats into markdown lines with title, category, tags, post summaries, and link.
    async ({ topic_id, post_limit = 5, start_post_number }, _extra: any) => {
      try {
        const { base, client } = ctx.siteState.ensureSelectedSite();
        const start = start_post_number ?? 1;
    
        // First request to load metadata/title and initial chunk
        let current = start;
        let fetchedPosts: Array<{ number: number; username: string; created_at: string; content: string }> = [];
        let slug = "";
        let title = `Topic ${topic_id}`;
        let category = "";
        let tags: string[] = [];
    
        const maxBatches = 10; // safety guard
        const limit = Number.isFinite(ctx.maxReadLength) ? ctx.maxReadLength : 50000;
        for (let i = 0; i < maxBatches && fetchedPosts.length < post_limit; i++) {
          // Ask for raw content when possible
          const url = current > 1 ? `/t/${topic_id}.json?near=${current}&include_raw=true` : `/t/${topic_id}.json?include_raw=true`;
          const data = (await client.get(url)) as any;
          if (i === 0) {
            title = data?.title || title;
            category = data?.category_id ? `Category ID ${data.category_id}` : "";
            tags = Array.isArray(data?.tags) ? data.tags : [];
            slug = data?.slug || String(topic_id);
          }
          const stream: any[] = Array.isArray(data?.post_stream?.posts) ? data.post_stream.posts : [];
          const sorted = stream.slice().sort((a, b) => (a.post_number || 0) - (b.post_number || 0));
          const filtered = sorted.filter((p) => (p.post_number || 0) >= current);
          for (const p of filtered) {
            if (fetchedPosts.length >= post_limit) break;
            fetchedPosts.push({
              number: p.post_number,
              username: p.username,
              created_at: p.created_at,
              content: (p.raw || p.cooked || p.excerpt || "").toString().slice(0, limit),
            });
          }
          if (filtered.length === 0) break; // no progress
          current = (filtered[filtered.length - 1]?.post_number || current) + 1;
        }
    
        const lines: string[] = [];
        lines.push(`# ${title}`);
        if (category) lines.push(category);
        if (tags.length) lines.push(`Tags: ${tags.join(", ")}`);
        lines.push("");
        for (const p of fetchedPosts) {
          lines.push(`- Post #${p.number} by @${p.username} (${p.created_at})`);
          lines.push(`  ${p.content}`);
        }
        lines.push("");
        lines.push(`Link: ${base}/t/${slug}/${topic_id}`);
        return { content: [{ type: "text", text: lines.join("\n") }] };
      } catch (e: any) {
        return { content: [{ type: "text", text: `Failed to read topic ${topic_id}: ${e?.message || String(e)}` }], isError: true };
      }
    }
  • Input schema using Zod: requires topic_id (positive integer), optional post_limit (1-100, default 5), optional start_post_number (min 1).
    const schema = z.object({
      topic_id: z.number().int().positive(),
      post_limit: z.number().int().min(1).max(100).optional(),
      start_post_number: z.number().int().min(1).optional().describe("Start from this post number (1-based)")
    });
  • Registers the discourse_read_topic tool on the MCP server, providing title, description, inputSchema, and inline handler function.
    server.registerTool(
      "discourse_read_topic",
      {
        title: "Read Topic",
        description: "Read a topic metadata and first N posts.",
        inputSchema: schema.shape,
      },
      async ({ topic_id, post_limit = 5, start_post_number }, _extra: any) => {
        try {
          const { base, client } = ctx.siteState.ensureSelectedSite();
          const start = start_post_number ?? 1;
    
          // First request to load metadata/title and initial chunk
          let current = start;
          let fetchedPosts: Array<{ number: number; username: string; created_at: string; content: string }> = [];
          let slug = "";
          let title = `Topic ${topic_id}`;
          let category = "";
          let tags: string[] = [];
    
          const maxBatches = 10; // safety guard
          const limit = Number.isFinite(ctx.maxReadLength) ? ctx.maxReadLength : 50000;
          for (let i = 0; i < maxBatches && fetchedPosts.length < post_limit; i++) {
            // Ask for raw content when possible
            const url = current > 1 ? `/t/${topic_id}.json?near=${current}&include_raw=true` : `/t/${topic_id}.json?include_raw=true`;
            const data = (await client.get(url)) as any;
            if (i === 0) {
              title = data?.title || title;
              category = data?.category_id ? `Category ID ${data.category_id}` : "";
              tags = Array.isArray(data?.tags) ? data.tags : [];
              slug = data?.slug || String(topic_id);
            }
            const stream: any[] = Array.isArray(data?.post_stream?.posts) ? data.post_stream.posts : [];
            const sorted = stream.slice().sort((a, b) => (a.post_number || 0) - (b.post_number || 0));
            const filtered = sorted.filter((p) => (p.post_number || 0) >= current);
            for (const p of filtered) {
              if (fetchedPosts.length >= post_limit) break;
              fetchedPosts.push({
                number: p.post_number,
                username: p.username,
                created_at: p.created_at,
                content: (p.raw || p.cooked || p.excerpt || "").toString().slice(0, limit),
              });
            }
            if (filtered.length === 0) break; // no progress
            current = (filtered[filtered.length - 1]?.post_number || current) + 1;
          }
    
          const lines: string[] = [];
          lines.push(`# ${title}`);
          if (category) lines.push(category);
          if (tags.length) lines.push(`Tags: ${tags.join(", ")}`);
          lines.push("");
          for (const p of fetchedPosts) {
            lines.push(`- Post #${p.number} by @${p.username} (${p.created_at})`);
            lines.push(`  ${p.content}`);
          }
          lines.push("");
          lines.push(`Link: ${base}/t/${slug}/${topic_id}`);
          return { content: [{ type: "text", text: lines.join("\n") }] };
        } catch (e: any) {
          return { content: [{ type: "text", text: `Failed to read topic ${topic_id}: ${e?.message || String(e)}` }], isError: true };
        }
      }
    );
  • Top-level call to register the read_topic module's tools in the main registry function registerAllTools.
    registerReadTopic(server, ctx, { allowWrites: false });
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It implies a read-only operation but doesn't disclose authentication needs, rate limits, error conditions, or what happens if parameters are invalid. The phrase 'first N posts' hints at pagination but lacks details on ordering or truncation 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 a single, efficient sentence that front-loads the core functionality. Every word earns its place without redundancy, making it easy to parse quickly. No extraneous details or verbose explanations are included.

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 complexity of a 3-parameter tool with no annotations and no output schema, the description is insufficient. It doesn't explain return values, error handling, or important constraints like what 'metadata' includes or how posts are ordered. For a read operation with multiple parameters, more context is needed for effective use.

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

Parameters3/5

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

Schema description coverage is low at 33%, with only 'start_post_number' described. The description adds value by clarifying that 'first N posts' corresponds to the 'post_limit' parameter, but doesn't explain 'topic_id' semantics or default behaviors. It partially compensates for the coverage gap but leaves key parameters underspecified.

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

Purpose4/5

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

The description clearly states the verb ('Read') and resource ('topic metadata and first N posts'), making the purpose understandable. It distinguishes from siblings like discourse_read_post (which reads a single post) and discourse_filter_topics (which lists topics). However, it doesn't explicitly mention what 'metadata' includes or how it differs from full topic content, keeping it from a perfect score.

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?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention when to choose discourse_read_topic over discourse_read_post for post content, or how it complements discourse_filter_topics for topic discovery. There's no context about prerequisites or typical use cases.

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

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ahnmichael/gitlab-forum-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server