Skip to main content
Glama
discourse

Discourse MCP

Official
by discourse

discourse_get_draft

Retrieve saved draft content from Discourse forums using specific keys like 'new_topic' for new topics or 'topic_' for replies. Access partially composed posts to continue editing where you left off.

Instructions

Retrieve a specific draft by its key. Common keys: "new_topic" for new topic drafts, "topic_" for reply drafts.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
draft_keyYesDraft key (e.g., "new_topic", "topic_123", "new_private_message")
sequenceNoExpected sequence number (optional)

Implementation Reference

  • The handler function for the discourse_get_draft tool. It fetches the draft from the Discourse API using the provided draft_key and optional sequence, parses the JSON data, formats a markdown response with preview and full JSON, and handles errors.
    async (input: unknown, _extra: unknown) => {
      const { draft_key, sequence } = schema.parse(input);
    
      try {
        const { client } = ctx.siteState.ensureSelectedSite();
        const params = new URLSearchParams();
        if (typeof sequence === "number") params.set("sequence", String(sequence));
    
        const url = `/drafts/${encodeURIComponent(draft_key)}.json${params.toString() ? `?${params}` : ""}`;
        const data = (await client.get(url)) as {
          draft?: string;
          draft_sequence?: number;
        };
    
        if (!data?.draft) {
          return { content: [{ type: "text", text: `No draft found for key "${draft_key}".` }] };
        }
    
        let parsedDraft: Record<string, unknown> = {};
        try {
          parsedDraft = JSON.parse(data.draft);
        } catch {
          parsedDraft = { raw: data.draft };
        }
    
        const lines = [`# Draft: \`${draft_key}\`\n`];
        lines.push(`**Sequence:** ${data.draft_sequence ?? "unknown"}`);
    
        if (parsedDraft.title) lines.push(`**Title:** ${parsedDraft.title}`);
        if (parsedDraft.categoryId) lines.push(`**Category ID:** ${parsedDraft.categoryId}`);
        if (parsedDraft.tags && Array.isArray(parsedDraft.tags)) {
          lines.push(`**Tags:** ${(parsedDraft.tags as string[]).join(", ")}`);
        }
        if (parsedDraft.action) lines.push(`**Action:** ${parsedDraft.action}`);
    
        if (parsedDraft.reply) {
          lines.push(`\n**Content:**\n${parsedDraft.reply}`);
        }
    
        lines.push("\n```json");
        lines.push(
          JSON.stringify(
            {
              draft_key,
              draft_sequence: data.draft_sequence,
              data: parsedDraft,
            },
            null,
            2
          )
        );
        lines.push("```");
    
        return { content: [{ type: "text", text: lines.join("\n") }] };
      } catch (e: unknown) {
        const msg = e instanceof Error ? e.message : String(e);
        return { content: [{ type: "text", text: `Failed to get draft: ${msg}` }], isError: true };
      }
    }
  • Zod input schema defining draft_key (required string) and optional sequence (number). Used for validation in the tool handler.
    const schema = z.object({
      draft_key: z
        .string()
        .min(1)
        .max(40)
        .describe('Draft key (e.g., "new_topic", "topic_123", "new_private_message")'),
      sequence: z.number().int().min(0).optional().describe("Expected sequence number (optional)"),
    });
  • Registration of the discourse_get_draft tool using server.registerTool, including name, metadata (title, description, inputSchema), and handler function.
    server.registerTool(
      "discourse_get_draft",
      {
        title: "Get Draft",
        description:
          'Retrieve a specific draft by its key. Common keys: "new_topic" for new topic drafts, "topic_<id>" for reply drafts.',
        inputSchema: schema.shape,
      },
      async (input: unknown, _extra: unknown) => {
        const { draft_key, sequence } = schema.parse(input);
    
        try {
          const { client } = ctx.siteState.ensureSelectedSite();
          const params = new URLSearchParams();
          if (typeof sequence === "number") params.set("sequence", String(sequence));
    
          const url = `/drafts/${encodeURIComponent(draft_key)}.json${params.toString() ? `?${params}` : ""}`;
          const data = (await client.get(url)) as {
            draft?: string;
            draft_sequence?: number;
          };
    
          if (!data?.draft) {
            return { content: [{ type: "text", text: `No draft found for key "${draft_key}".` }] };
          }
    
          let parsedDraft: Record<string, unknown> = {};
          try {
            parsedDraft = JSON.parse(data.draft);
          } catch {
            parsedDraft = { raw: data.draft };
          }
    
          const lines = [`# Draft: \`${draft_key}\`\n`];
          lines.push(`**Sequence:** ${data.draft_sequence ?? "unknown"}`);
    
          if (parsedDraft.title) lines.push(`**Title:** ${parsedDraft.title}`);
          if (parsedDraft.categoryId) lines.push(`**Category ID:** ${parsedDraft.categoryId}`);
          if (parsedDraft.tags && Array.isArray(parsedDraft.tags)) {
            lines.push(`**Tags:** ${(parsedDraft.tags as string[]).join(", ")}`);
          }
          if (parsedDraft.action) lines.push(`**Action:** ${parsedDraft.action}`);
    
          if (parsedDraft.reply) {
            lines.push(`\n**Content:**\n${parsedDraft.reply}`);
          }
    
          lines.push("\n```json");
          lines.push(
            JSON.stringify(
              {
                draft_key,
                draft_sequence: data.draft_sequence,
                data: parsedDraft,
              },
              null,
              2
            )
          );
          lines.push("```");
    
          return { content: [{ type: "text", text: lines.join("\n") }] };
        } catch (e: unknown) {
          const msg = e instanceof Error ? e.message : String(e);
          return { content: [{ type: "text", text: `Failed to get draft: ${msg}` }], isError: true };
        }
      }
    );

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/discourse/discourse-mcp'

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