Skip to content

Instantly share code, notes, and snippets.

@mhart
Created August 26, 2025 05:06
Show Gist options
  • Select an option

  • Save mhart/0d47102b7a9dd85aff259930187d224d to your computer and use it in GitHub Desktop.

Select an option

Save mhart/0d47102b7a9dd85aff259930187d224d to your computer and use it in GitHub Desktop.
Agents SDK MCP Server with state based on URL
import { McpAgent } from "agents/mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
type Props = {
org: string;
project: string;
};
type State = {
org?: string;
project?: string;
};
export class MyMCP extends McpAgent<Env, State, Props> {
server = new McpServer({
name: "MCP Server with Props",
version: "1.0.0",
});
async init() {
// Only set if not already set (ie, first request for session)
if (this.state?.org == null) {
this.setState(this.props);
}
this.server.tool("whoami", async () => ({
content: [
{
type: "text",
text: `Org: ${this.state.org}, Project: ${this.state.project}`,
},
],
}));
}
}
export default {
fetch(request: Request, env: Env, ctx: ExecutionContext) {
const url = new URL(request.url);
if (url.pathname === "/sse" || url.pathname === "/sse/message") {
return MyMCP.serveSSE("/sse").fetch(request, env, ctx);
}
const pattern = new URLPattern({ pathname: "/mcp/:org?/:project?" });
const result = pattern.exec(url);
if (result) {
const { groups } = result.pathname;
ctx.props.org = groups?.org ?? "";
ctx.props.project = groups?.project ?? "";
return MyMCP.serve(pattern.pathname).fetch(request, env, ctx);
}
return new Response("Not found", { status: 404 });
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment