How to integrate Stack exchange MCP with Mastra AI

Trusted by
AWS
Glean
Zoom
Airtable

30 min · no commitment · see it on your stack

Stack exchange logo
Mastra AI logo
divider

Introduction

This guide walks you through connecting Stack exchange to Mastra AI using the Composio tool router. By the end, you'll have a working Stack exchange agent that can find top-voted javascript questions this week, list all collectives on stack overflow, show recent comments on your math stackexchange post through natural language commands.

This guide will help you understand how to give your Mastra AI agent real control over a Stack exchange account through Composio's Stack exchange MCP server.

Before we dive in, let's take a quick look at the key ideas and tools involved.

Also integrate Stack exchange with

TL;DR

Here's what you'll learn:
  • Set up your environment so Mastra, OpenAI, and Composio work together
  • Create a Tool Router session in Composio that exposes Stack exchange tools
  • Connect Mastra's MCP client to the Composio generated MCP URL
  • Fetch Stack exchange tool definitions and attach them as a toolset
  • Build a Mastra agent that can reason, call tools, and return structured results
  • Run an interactive CLI where you can chat with your Stack exchange agent

What is Mastra AI?

Mastra AI is a TypeScript framework for building AI agents with tool support. It provides a clean API for creating agents that can use external services through MCP.

Key features include:

  • MCP Client: Built-in support for Model Context Protocol servers
  • Toolsets: Organize tools into logical groups
  • Step Callbacks: Monitor and debug agent execution
  • OpenAI Integration: Works with OpenAI models via @ai-sdk/openai

What is the Stack exchange MCP server, and what's possible with it?

The Stack exchange MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your Stack Exchange account. It provides structured and secure access to your Stack Exchange activity, so your agent can perform actions like searching questions, exploring collectives, retrieving comments, and analyzing post revisions on your behalf.

  • Powerful question search and discovery: Instantly ask your agent to search for Stack Exchange questions by keyword or tag, helping you find relevant discussions and solutions faster.
  • Collectives and tags exploration: Have your agent retrieve lists of collectives and their associated tags, making it easy to discover expert communities and filter content by topic.
  • Comment management and flagging: Let your agent fetch comments from specific sites and check valid flag options, streamlining comment moderation and participation.
  • Revision history analysis: Direct your agent to retrieve and review the full edit history of posts, enabling transparent audits or understanding how answers evolve over time.
  • Site discovery and navigation: Use your agent to list all available Stack Exchange sites and their API parameters, ensuring you always target the right community for your needs.

Supported Tools & Triggers

Tools
Create FilterTool to create a custom filter for Stack Exchange API responses.
Find Similar QuestionsTool to find questions similar to a hypothetical one based on a title and optional tag combination.
Get Access TokensTool to read the properties for a set of access tokens obtained via OAuth 2.
Get Answer CommentsTool to retrieve comments on a set of answers from Stack Exchange.
Get Answer Flag OptionsTool to fetch valid flag options for a specific answer.
Get Answers By IDsTool to retrieve a set of answers by their IDs from a Stack Exchange site.
Get Badge Recipients By IDsTool to retrieve recently awarded badges constrained to a specific set of badge IDs.
Get Badges By IDsTool to retrieve badges by their IDs on a Stack Exchange site.
Get Collective AnswersTool to retrieve answers belonging to the specified collective(s) on a Stack Exchange site.
Get Collective QuestionsTool to retrieve questions associated with the specified collective.
Get CollectivesTool to retrieve all collectives on a Stack Exchange site in alphabetical order.
Get Collectives By SlugsTool to retrieve Collective objects by their slugs from a Stack Exchange site.
Get Collective TagsRetrieve tags associated with specified Stack Overflow collectives.
Get Collective UsersTool to retrieve users who are members of the specified Collectives on Stack Exchange.
Get Comment Flag OptionsTool to fetch valid flag options for a given comment.
Get CommentsRetrieves comments from a Stack Exchange site (e.
Get Comments By IDsTool to retrieve specific comments by their IDs from a Stack Exchange site.
Get EventsRetrieves a stream of recent events that occurred on a Stack Exchange site.
Get Filters By IDsTool to retrieve the fields included by the given filters and the safeness of those filters.
Get Linked QuestionsTool to get questions which link to those questions identified in the ids parameter.
Get MeTool to retrieve the authenticated user's profile information from Stack Exchange.
Get My AchievementsRetrieves the authenticated user's recent network-wide achievements across all Stack Exchange sites.
Get My Associated AccountsTool to retrieve all Stack Exchange accounts associated with the authenticated user.
Get My Featured QuestionsTool to retrieve questions with active bounties offered by the authenticated user.
Get My MentionsTool to retrieve comments mentioning the authenticated user on a Stack Exchange site.
Get My Merge HistoryTool to retrieve account merge history for the authenticated user.
Get My Network ActivityTool to retrieve a summary of the authenticated user's activity across the Stack Exchange network.
Get My No Answer QuestionsTool to retrieve questions owned by the authenticated user that have no answers.
Get My PostsTool to retrieve posts (questions and answers) owned by the authenticated user from a Stack Exchange site.
Get My PrivilegesTool to retrieve privileges for the authenticated user on a Stack Exchange site.
Get My QuestionsTool to retrieve questions owned by the authenticated user on a Stack Exchange site.
Get My ReputationTool to retrieve reputation changes for the authenticated user on a Stack Exchange site.
Get My Reputation HistoryTool to retrieve the authenticated user's public reputation history on a Stack Exchange site.
Get My Suggested EditsTool to retrieve suggested edits submitted by the authenticated user on a Stack Exchange site.
Get My Tag PreferencesTool to retrieve tag preferences for the authenticated user on a Stack Exchange site.
Get My TagsTool to retrieve tags the authenticated user is active in on a Stack Exchange site.
Get My TimelineTool to retrieve a timeline of actions the authenticated user has taken on a Stack Exchange site.
Get My Top Answers In TagsTool to retrieve the top 30 answers the authenticated user has posted in response to questions with specific tags.
Get My Top Answer TagsTool to retrieve the authenticated user's top 30 tags by answer score on a Stack Exchange site.
Get My Top Questions In TagsTool to retrieve the top 30 questions the authenticated user has posted in response to questions with the given tags.
Get My Top Question TagsTool to retrieve the authenticated user's top 30 tags by question score on a Stack Exchange site.
Get My Top TagsTool to retrieve the authenticated user's top 30 tags by combined question and answer score on a Stack Exchange site.
Get My Unaccepted QuestionsTool to retrieve questions owned by the authenticated user that have no accepted answer.
Get My Unanswered QuestionsTool to retrieve questions owned by the authenticated user that are not considered answered.
Get Post CommentsTool to retrieve comments on posts identified by IDs, regardless of post type (question or answer).
Get Posts By IDsTool to retrieve a set of posts by their IDs from a Stack Exchange site.
Get Post Suggested EditsTool to retrieve suggested edits on posts from a Stack Exchange site.
Get Question AnswersTool to retrieve all answers for a set of questions identified by their IDs.
Get Question Close OptionsTool to fetch flag options that make up close reasons for a specific question.
Get Question CommentsTool to retrieve comments on a set of questions from Stack Exchange.
Get Question Flag OptionsTool to fetch valid flag options, including close reasons, for a specific question.
Get QuestionsTool to retrieve a list of questions from a Stack Exchange site without requiring tags or keywords.
Get Questions By Answer IDsTool to retrieve questions that specific answers belong to on a Stack Exchange site.
Get Questions By IDsTool to retrieve a set of questions by their IDs from a Stack Exchange site.
Get Question TimelineTool to retrieve timeline events for specified questions on a Stack Exchange site.
Get Related TagsTool to retrieve tags most related to the specified tags on a Stack Exchange site.
Get Revisions By IDsTool to retrieve revisions for specific posts by their IDs.
Search QuestionsTool to search the site for questions meeting certain criteria.
Get Site InfoTool to retrieve comprehensive statistics and information about a Stack Exchange site.
Get SitesRetrieves a comprehensive list of all Stack Exchange network sites with detailed information including site names, URLs, styling, and api_site_parameter values needed for other API calls.
Get Suggested Edits By IDsTool to retrieve suggested edits by their IDs from a Stack Exchange site.
Get Tag FAQTool to retrieve frequently asked questions for a set of tags on Stack Exchange.
Get Tag InfoTool to retrieve tag objects representing specified tags on a Stack Exchange site.
Get Tag SynonymsTool to retrieve all synonyms that point to the specified tags on a Stack Exchange site.
Get Tag Top AnswerersTool to retrieve the top 30 answerers active in a single tag, of either all-time or the last 30 days.
Get Tag Top AskersTool to retrieve the top askers active in a single tag.
Get Tag WikisTool to retrieve wiki content for specified tags on a Stack Exchange site.
Get User AnswersTool to retrieve answers posted by specific users on a Stack Exchange site.
Get User Associated AccountsTool to retrieve all Stack Exchange accounts associated with specified users by their account IDs.
Get User BadgesTool to retrieve badges earned by specified users on a Stack Exchange site.
Get User CommentsTool to retrieve comments posted by specified users on a Stack Exchange site.
Get User Comments To UserTool to retrieve comments that specific users have posted in reply to a single user.
Get User FavoritesTool to retrieve the questions that users have favorited/bookmarked.
Get User Featured QuestionsTool to retrieve questions with active bounties offered by specified users.
Get User Full Reputation HistoryTool to retrieve a user's full reputation history on a Stack Exchange site, including private events.
Get User InboxTool to retrieve a user's inbox from Stack Exchange.
Get User MentionsTool to retrieve comments that mention specific users on a Stack Exchange site.
Get User Merge HistoryTool to retrieve account merge history for specified user account IDs across the Stack Exchange network.
Get User No Answer QuestionsTool to retrieve questions asked by specified users that have zero undeleted answers.
Get User NotificationsTool to retrieve notifications for a specific Stack Exchange user by ID.
Get User PostsTool to retrieve posts (questions and answers) posted by specific users on a Stack Exchange site.
Get User PrivilegesTool to retrieve privileges a specific user has on a Stack Exchange site.
Get User QuestionsTool to retrieve questions asked by specific users on a Stack Exchange site.
Get User ReputationTool to retrieve reputation changes for users on a Stack Exchange site.
Get User Reputation HistoryTool to retrieve public reputation history for specified Stack Exchange users.
Get Users By IDsTool to retrieve user profiles by their IDs from a Stack Exchange site.
Get User Suggested EditsTool to retrieve suggested edits submitted by specified users on a Stack Exchange site.
Get User TagsTool to retrieve tags that specified users are active in on a Stack Exchange site.
Get User TimelineTool to retrieve a timeline of actions taken by specified users on a Stack Exchange site.
Get User Top Answers In TagsTool to retrieve the top 30 answers a specific user has posted in response to questions with given tags.
Get User Top Answer TagsTool to retrieve a single user's top tags by answer score on Stack Exchange.
Get User Top Questions In TagsTool to retrieve the top 30 questions a user has asked with the given tags.
Get User Top Question TagsTool to retrieve a single user's top tags by question score on a Stack Exchange site.
Get User Top TagsTool to retrieve a single user's top tags by combined question and answer score on a Stack Exchange site.
Get User Unaccepted QuestionsTool to retrieve questions asked by specified users that have at least one answer but no accepted answer.
Get User Unanswered QuestionsTool to retrieve questions asked by specific users that the site considers unanswered.
Get User Unread InboxTool to retrieve unread items in a specific user's Stack Exchange inbox.
Get User Unread NotificationsTool to retrieve unread notifications for a specific user on Stack Exchange.
List AnswersTool to retrieve all undeleted answers from a Stack Exchange site.
List Badge RecipientsTool to retrieve recently awarded badges from a Stack Exchange site.
List BadgesTool to retrieve all badges available in a Stack Exchange site.
List Elected ModeratorsTool to retrieve users who have moderator powers and were actually elected on a Stack Exchange site.
List ErrorsTool to retrieve the various error codes that can be produced by the Stack Exchange API.
List Featured QuestionsTool to retrieve all questions with active bounties in the system.
List Moderator Only TagsTool to retrieve tags that only moderators can use on a Stack Exchange site.
List ModeratorsTool to retrieve users who can exercise moderation powers on a Stack Exchange site.
List Named BadgesTool to retrieve all explicitly named badges from a Stack Exchange site.
List No Answer QuestionsTool to retrieve questions that have received no answers from a Stack Exchange site.
List PostsTool to retrieve all posts (questions and answers) from a Stack Exchange site.
List PrivilegesTool to retrieve all earnable privileges on a Stack Exchange site.
List Required TagsTool to retrieve tags found on a site that fulfill required tag constraints on questions.
List Suggested EditsTool to retrieve all suggested edits in a Stack Exchange site.
List Tag BadgesReturns badges awarded for participation in specific tags on Stack Exchange sites.
List TagsTool to retrieve tags found on a Stack Exchange site.
List Tag SynonymsTool to retrieve all tag synonyms found on a Stack Exchange site.
List Unanswered QuestionsTool to retrieve questions the site considers to be unanswered.
List Unanswered Questions My TagsTool to retrieve unanswered questions within the authenticated user's favorite or frequented tags.
List UsersTool to retrieve all users on a Stack Exchange site.
Render AnswerTool to render a preview of an answer given its body and the question it's on.
Advanced SearchTool to search a Stack Exchange site for questions matching advanced criteria.
Search ExcerptsTool to search a Stack Exchange site for items matching given criteria with excerpt snippets.

What is the Composio tool router, and how does it fit here?

What is Composio SDK?

Composio's Composio SDK helps agents find the right tools for a task at runtime. You can plug in multiple toolkits (like Gmail, HubSpot, and GitHub), and the agent will identify the relevant app and action to complete multi-step workflows. This can reduce token usage and improve the reliability of tool calls. Read more here: Getting started with Composio SDK

The tool router generates a secure MCP URL that your agents can access to perform actions.

How the Composio SDK works

The Composio SDK follows a three-phase workflow:

  1. Discovery: Searches for tools matching your task and returns relevant toolkits with their details.
  2. Authentication: Checks for active connections. If missing, creates an auth config and returns a connection URL via Auth Link.
  3. Execution: Executes the action using the authenticated connection.

Step-by-step Guide

Prerequisites

Before starting, make sure you have:
  • Node.js 18 or higher
  • A Composio account with an active API key
  • An OpenAI API key
  • Basic familiarity with TypeScript

Getting API Keys for OpenAI and Composio

OpenAI API Key
  • Go to the OpenAI dashboard and create an API key.
  • You need credits or a connected billing setup to use the models.
  • Store the key somewhere safe.
Composio API Key
  • Log in to the Composio dashboard.
  • Go to Settings and copy your API key.
  • This key lets your Mastra agent talk to Composio and reach Stack exchange through MCP.

Install dependencies

bash
npm install @composio/core @mastra/core @mastra/mcp @ai-sdk/openai dotenv

Install the required packages.

What's happening:

  • @composio/core is the Composio SDK for creating MCP sessions
  • @mastra/core provides the Agent class
  • @mastra/mcp is Mastra's MCP client
  • @ai-sdk/openai is the model wrapper for OpenAI
  • dotenv loads environment variables from .env

Set up environment variables

bash
COMPOSIO_API_KEY=your_composio_api_key_here
COMPOSIO_USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key_here

Create a .env file in your project root.

What's happening:

  • COMPOSIO_API_KEY authenticates your requests to Composio
  • COMPOSIO_USER_ID tells Composio which user this session belongs to
  • OPENAI_API_KEY lets the Mastra agent call OpenAI models

Import libraries and validate environment

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({
  apiKey: composioAPIKey as string,
});
What's happening:
  • dotenv/config auto loads your .env so process.env.* is available
  • openai gives you a Mastra compatible model wrapper
  • Agent is the Mastra agent that will call tools and produce answers
  • MCPClient connects Mastra to your Composio MCP server
  • Composio is used to create a Tool Router session

Create a Tool Router session for Stack exchange

typescript
async function main() {
  const session = await composio.create(
    composioUserID as string,
    {
      toolkits: ["stack_exchange"],
    },
  );

  const composioMCPUrl = session.mcp.url;
  console.log("Stack exchange MCP URL:", composioMCPUrl);
What's happening:
  • create spins up a short-lived MCP HTTP endpoint for this user
  • The toolkits array contains "stack_exchange" for Stack exchange access
  • session.mcp.url is the MCP URL that Mastra's MCPClient will connect to

Configure Mastra MCP client and fetch tools

typescript
const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      nasdaq: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

console.log("Fetching MCP tools from Composio...");
const composioTools = await mcpClient.getTools();
console.log("Number of tools:", Object.keys(composioTools).length);
What's happening:
  • MCPClient takes an id for this client and a list of MCP servers
  • The headers property includes the x-api-key for authentication
  • getTools fetches the tool definitions exposed by the Stack exchange toolkit

Create the Mastra agent

typescript
const agent = new Agent({
    name: "stack_exchange-mastra-agent",
    instructions: "You are an AI agent with Stack exchange tools via Composio.",
    model: "openai/gpt-5",
  });
What's happening:
  • Agent is the core Mastra agent
  • name is just an identifier for logging and debugging
  • instructions guide the agent to use tools instead of only answering in natural language
  • model uses openai("gpt-5") to configure the underlying LLM

Set up interactive chat interface

typescript
let messages: AiMessageType[] = [];

console.log("Chat started! Type 'exit' or 'quit' to end.\n");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: "> ",
});

rl.prompt();

rl.on("line", async (userInput: string) => {
  const trimmedInput = userInput.trim();

  if (["exit", "quit", "bye"].includes(trimmedInput.toLowerCase())) {
    console.log("\nGoodbye!");
    rl.close();
    process.exit(0);
  }

  if (!trimmedInput) {
    rl.prompt();
    return;
  }

  messages.push({
    id: crypto.randomUUID(),
    role: "user",
    content: trimmedInput,
  });

  console.log("\nAgent is thinking...\n");

  try {
    const response = await agent.generate(messages, {
      toolsets: {
        stack_exchange: composioTools,
      },
      maxSteps: 8,
    });

    const { text } = response;

    if (text && text.trim().length > 0) {
      console.log(`Agent: ${text}\n`);
        messages.push({
          id: crypto.randomUUID(),
          role: "assistant",
          content: text,
        });
      }
    } catch (error) {
      console.error("\nError:", error);
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    console.log("\nSession ended.");
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main().catch((err) => {
  console.error("Fatal error:", err);
  process.exit(1);
});
What's happening:
  • messages keeps the full conversation history in Mastra's expected format
  • agent.generate runs the agent with conversation history and Stack exchange toolsets
  • maxSteps limits how many tool calls the agent can take in a single run
  • onStepFinish is a hook that prints intermediate steps for debugging

Complete Code

Here's the complete code to get you started with Stack exchange and Mastra AI:

typescript
import "dotenv/config";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { MCPClient } from "@mastra/mcp";
import { Composio } from "@composio/core";
import * as readline from "readline";

import type { AiMessageType } from "@mastra/core/agent";

const openaiAPIKey = process.env.OPENAI_API_KEY;
const composioAPIKey = process.env.COMPOSIO_API_KEY;
const composioUserID = process.env.COMPOSIO_USER_ID;

if (!openaiAPIKey) throw new Error("OPENAI_API_KEY is not set");
if (!composioAPIKey) throw new Error("COMPOSIO_API_KEY is not set");
if (!composioUserID) throw new Error("COMPOSIO_USER_ID is not set");

const composio = new Composio({ apiKey: composioAPIKey as string });

async function main() {
  const session = await composio.create(composioUserID as string, {
    toolkits: ["stack_exchange"],
  });

  const composioMCPUrl = session.mcp.url;

  const mcpClient = new MCPClient({
    id: composioUserID as string,
    servers: {
      stack_exchange: {
        url: new URL(composioMCPUrl),
        requestInit: {
          headers: session.mcp.headers,
        },
      },
    },
    timeout: 30_000,
  });

  const composioTools = await mcpClient.getTools();

  const agent = new Agent({
    name: "stack_exchange-mastra-agent",
    instructions: "You are an AI agent with Stack exchange tools via Composio.",
    model: "openai/gpt-5",
  });

  let messages: AiMessageType[] = [];

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: "> ",
  });

  rl.prompt();

  rl.on("line", async (input: string) => {
    const trimmed = input.trim();
    if (["exit", "quit"].includes(trimmed.toLowerCase())) {
      rl.close();
      return;
    }

    messages.push({ id: crypto.randomUUID(), role: "user", content: trimmed });

    const { text } = await agent.generate(messages, {
      toolsets: { stack_exchange: composioTools },
      maxSteps: 8,
    });

    if (text) {
      console.log(`Agent: ${text}\n`);
      messages.push({ id: crypto.randomUUID(), role: "assistant", content: text });
    }

    rl.prompt();
  });

  rl.on("close", async () => {
    await mcpClient.disconnect();
    process.exit(0);
  });
}

main();

Conclusion

You've built a Mastra AI agent that can interact with Stack exchange through Composio's Tool Router. You can extend this further by:
  • Adding other toolkits like Gmail, Slack, or GitHub
  • Building a web-based chat interface around this agent
  • Using multiple MCP endpoints to enable cross-app workflows

How to build Stack exchange MCP Agent with another framework

FAQ

What are the differences in Tool Router MCP and Stack exchange MCP?

With a standalone Stack exchange MCP server, the agents and LLMs can only access a fixed set of Stack exchange tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from Stack exchange and many other apps based on the task at hand, all through a single MCP endpoint.

Can I use Tool Router MCP with Mastra AI?

Yes, you can. Mastra AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right Stack exchange tools.

Can I manage the permissions and scopes for Stack exchange while using Tool Router?

Yes, absolutely. You can configure which Stack exchange scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your Stack exchange data and credentials are handled as safely as possible.

Used by agents from

Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai
Context
Letta
glean
HubSpot
Agent.ai
Altera
DataStax
Entelligence
Rolai

Never worry about agent reliability

We handle tool reliability, observability, and security so you never have to second-guess an agent action.