Created
August 26, 2025 05:06
-
-
Save mhart/0d47102b7a9dd85aff259930187d224d to your computer and use it in GitHub Desktop.
Agents SDK MCP Server with state based on URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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