Skip to main content
Glama

create_post

Create and publish new posts to Reddit subreddits, including text submissions or link sharing with specified titles and content.

Instructions

Create a new post in a subreddit

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
subredditYesName of the subreddit to post in
titleYesTitle of the post
contentYesContent of the post (text for self posts, URL for link posts)
is_selfNoWhether this is a self (text) post (true) or link post (false)

Implementation Reference

  • Primary MCP tool handler for 'create_post'. Takes parameters, calls RedditClient.createPost, formats response with post details and links, handles errors with localized messages.
    export async function createPost(params: {
      subreddit: string;
      title: string;
      content: string;
      is_self?: boolean;
    }) {
      const { subreddit, title, content, is_self = true } = params;
      const client = getRedditClient();
    
      if (!client) {
        throw new McpError(
          ErrorCode.InternalError,
          "Reddit client not initialized"
        );
      }
    
      try {
        console.log(
          `[Tool] Creating ${is_self ? "text" : "link"} post in r/${subreddit}: "${title}"`
        );
        
        const startTime = Date.now();
        const post = await client.createPost(subreddit, title, content, is_self);
        const endTime = Date.now();
        
        console.log(`[Tool] Post creation took ${endTime - startTime}ms`);
        
        const formattedPost = formatPostInfo(post);
    
        return {
          content: [
            {
              type: "text",
              text: `
    # ✅ Post créé avec succès !
    
    ## 📝 Détails du post
    - **Titre**: ${formattedPost.title}
    - **Subreddit**: r/${formattedPost.subreddit}
    - **Type**: ${formattedPost.type}
    - **ID**: ${post.id}
    - **Auteur**: u/${formattedPost.author}
    
    ## 🔗 Liens
    - **Lien complet**: ${formattedPost.links.fullPost}
    - **Permalink**: https://reddit.com${post.permalink}
    
    ## ⏰ Statut
    Votre post a été **publié avec succès** sur r/${formattedPost.subreddit} !
    
    ${is_self ? 
      `**Contenu**: ${content.substring(0, 200)}${content.length > 200 ? '...' : ''}` : 
      `**URL**: ${content}`
    }
              `,
            },
          ],
        };
      } catch (error: any) {
        console.error(`[Error] Error creating post: ${error}`);
        
        // Provide more specific error messages
        let errorMessage = `Échec de la création du post: ${error.message}`;
        
        if (error.message.includes('timeout')) {
          errorMessage = `⏰ Timeout lors de la création du post. Le post a peut-être été créé malgré tout - vérifiez votre profil Reddit.`;
        } else if (error.message.includes('authentication')) {
          errorMessage = `🔐 Problème d'authentification. Vérifiez vos credentials Reddit dans le fichier .env`;
        } else if (error.message.includes('rate limit')) {
          errorMessage = `⏱️ Limite de fréquence atteinte. Attendez quelques minutes avant de réessayer.`;
        } else if (error.message.includes('submission')) {
          errorMessage = `📝 Erreur de soumission. Vérifiez que le subreddit existe et que vous avez les permissions.`;
        }
        
        throw new McpError(
          ErrorCode.InternalError,
          errorMessage
        );
      }
    }
  • src/index.ts:180-207 (registration)
    Tool registration in MCP server's listTools response, defining name, description, and input schema with required parameters subreddit, title, content.
      name: "create_post",
      description: "Create a new post in a subreddit",
      inputSchema: {
        type: "object",
        properties: {
          subreddit: {
            type: "string",
            description: "Name of the subreddit to post in",
          },
          title: {
            type: "string",
            description: "Title of the post",
          },
          content: {
            type: "string",
            description:
              "Content of the post (text for self posts, URL for link posts)",
          },
          is_self: {
            type: "boolean",
            description:
              "Whether this is a self (text) post (true) or link post (false)",
            default: true,
          },
        },
        required: ["subreddit", "title", "content"],
      },
    },
  • src/index.ts:454-462 (registration)
    Dispatch handler in MCP server's CallToolRequestSchema switch statement, routing 'create_post' calls to tools.createPost with typed parameters.
    case "create_post":
      return await tools.createPost(
        toolParams as {
          subreddit: string;
          title: string;
          content: string;
          is_self?: boolean;
        }
      );
  • Core RedditClient helper method implementing the actual Reddit API submission for creating posts, handling authentication, API call to /api/submit, and post retrieval.
    async createPost(
      subreddit: string,
      title: string,
      content: string,
      isSelf: boolean = true
    ): Promise<RedditPost> {
      await this.authenticate();
    
      if (!this.username || !this.password) {
        throw new Error("User authentication required for posting");
      }
    
      try {
        console.log(`[Post] Creating post in r/${subreddit}: "${title}"`);
        
        const kind = isSelf ? "self" : "link";
        const params = new URLSearchParams();
        params.append("sr", subreddit);
        params.append("kind", kind);
        params.append("title", title);
        params.append(isSelf ? "text" : "url", content);
    
        const response = await this.api.post("/api/submit", params, {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          timeout: 30000, // 30 seconds timeout
        });
    
        console.log(`[Post] Reddit API response:`, response.data);
    
        if (response.data.success) {
          const postId = response.data.data.id;
          const postName = response.data.data.name;
          console.log(`[Post] Post created successfully! ID: ${postId}, Name: ${postName}`);
          
          try {
            // Try to get the newly created post
            const newPost = await this.getPost(postId);
            console.log(`[Post] Successfully retrieved created post`);
            return newPost;
          } catch (getError) {
            console.log(`[Post] Could not retrieve post details, but post was created successfully`);
            // Return a basic post object if we can't retrieve the full details
            return {
              id: postId,
              title: title,
              author: this.username!,
              subreddit: subreddit,
              selftext: isSelf ? content : "",
              url: isSelf ? "" : content,
              score: 1,
              upvoteRatio: 1.0,
              numComments: 0,
              createdUtc: Math.floor(Date.now() / 1000),
              over18: false,
              spoiler: false,
              edited: false,
              isSelf: isSelf,
              linkFlairText: "",
              permalink: `/r/${subreddit}/comments/${postId}/`,
            };
          }
        } else {
          console.error(`[Post] Reddit API returned success=false:`, response.data);
          const errors = response.data.errors || [];
          const errorMsg = errors.length > 0 ? errors.join(", ") : "Unknown error";
          throw new Error(`Failed to create post: ${errorMsg}`);
        }
      } catch (error: any) {
        console.error(`[Error] Failed to create post in r/${subreddit}:`, error);
        
        if (error.response) {
          console.error(`[Error] Reddit API error response:`, error.response.data);
          throw new Error(`Failed to create post: ${error.response.data?.message || error.message}`);
        } else if (error.code === 'ECONNABORTED') {
          console.error(`[Error] Request timeout when creating post`);
          throw new Error(`Post creation timed out - check Reddit manually to see if it was created`);
        } else {
          throw new Error(`Failed to create post in r/${subreddit}: ${error.message}`);
        }
      }
    }

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/samy-clivolt/reddit-mcp-server'

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