Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

protected-server.ts

170 lines5.9 KB

1import { createServer } from 'node:http'
2import { z } from 'zod'
3import {
4 McpServer,
5 WebStandardStreamableHTTPServerTransport,
6} from '@modelcontextprotocol/server'
7import type { IncomingMessage, Server } from 'node:http'
8​
9/** Copy the Node request headers into Web `Headers`. */
10function webHeaders(req: IncomingMessage) {
11 const headers = new Headers()
12 const entries = Object.entries(req.headersDistinct)
13 for (const [name, values] of entries) {
14 for (const value of values ?? []) headers.append(name, value)
15 }
16 return headers
18​
19/**
20 * A local MCP server behind OAuth, like Notion's or Linear's: protected
21 * resource metadata, authorization server metadata, dynamic client
22 * registration, a token endpoint, and an `echo` tool.
23 *
24 * - The code `code-1` gives `access-1` and `refresh-1`.
25 * - The code `code-2` gives only `access-1` (no refresh token, expiry, or scope).
26 * - The refresh token `refresh-1` gives `access-2` (and no new refresh token).
27 * - `revoke(token)` makes the MCP endpoint refuse a token.
28 */
29export async function startProtectedServer(
30 options: {
31 /** Advertise that callbacks carry `iss` (RFC 9207), as Linear does. */
32 issParameter?: boolean
33 } = {},
34) {
35 const seen = {
36 registrations: [] as Array<Record<string, unknown>>,
37 tokenRequests: [] as Array<URLSearchParams>,
38 }
39 const valid = new Set(['access-1'])
40 let base = ''
41 const readBody = async (req: IncomingMessage) => {
42 const chunks: Array<Buffer> = []
43 for await (const chunk of req) chunks.push(chunk as Buffer)
44 return Buffer.concat(chunks).toString('utf8')
45 }
46 const server: Server = createServer((req, res) => {
47 void (async () => {
48 const url = new URL(req.url ?? '/', base)
49 const json = (status: number, value: unknown) => {
50 res.writeHead(status, { 'Content-Type': 'application/json' })
51 res.end(JSON.stringify(value))
52 }
53 if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) {
54 return json(200, {
55 resource: `${base}/mcp`,
56 authorization_servers: [base],
57 })
58 }
59 if (url.pathname.startsWith('/.well-known/oauth-authorization-server')) {
60 return json(200, {
61 issuer: base,
62 authorization_endpoint: `${base}/authorize`,
63 token_endpoint: `${base}/token`,
64 registration_endpoint: `${base}/register`,
65 response_types_supported: ['code'],
66 grant_types_supported: ['authorization_code', 'refresh_token'],
67 code_challenge_methods_supported: ['S256'],
68 token_endpoint_auth_methods_supported: ['none'],
69 ...(options.issParameter
70 ? { authorization_response_iss_parameter_supported: true }
71 : {}),
72 })
73 }
74 if (url.pathname === '/register' && req.method === 'POST') {
75 const metadata = JSON.parse(await readBody(req))
76 seen.registrations.push(metadata)
77 return json(201, { ...metadata, client_id: 'client-1' })
78 }
79 if (url.pathname === '/token' && req.method === 'POST') {
80 const form = new URLSearchParams(await readBody(req))
81 seen.tokenRequests.push(form)
82 if (
83 form.get('grant_type') === 'authorization_code' &&
84 form.get('code') === 'code-1'
85 ) {
86 return json(200, {
87 access_token: 'access-1',
88 refresh_token: 'refresh-1',
89 token_type: 'Bearer',
90 expires_in: 3600,
91 scope: 'read write',
92 })
93 }
94 if (
95 form.get('grant_type') === 'authorization_code' &&
96 form.get('code') === 'code-2'
97 ) {
98 return json(200, { access_token: 'access-1', token_type: 'Bearer' })
99 }
100 if (
101 form.get('grant_type') === 'refresh_token' &&
102 form.get('refresh_token') === 'refresh-1'
103 ) {
104 valid.add('access-2')
105 return json(200, { access_token: 'access-2', token_type: 'Bearer' })
106 }
107 return json(400, { error: 'invalid_grant' })
108 }
109 if (url.pathname === '/mcp') {
110 const token = (req.headers.authorization ?? '').replace(/^Bearer /, '')
111 if (!valid.has(token)) {
112 res.writeHead(401, {
113 'WWW-Authenticate': `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`,
114 })
115 res.end()
116 return
117 }
118 if (req.method !== 'POST') {
119 res.writeHead(405).end()
120 return
121 }
122 const mcp = new McpServer({ name: 'protected', version: '1.0.0' })
123 mcp.registerTool(
124 'echo',
125 {
126 description: 'Echo text',
127 inputSchema: z.object({ text: z.string() }),
128 annotations: { readOnlyHint: true },
129 },
130 async ({ text }) => ({
131 content: [{ type: 'text' as const, text: `echo: ${text}` }],
132 }),
133 )
134 const transport = new WebStandardStreamableHTTPServerTransport({
135 sessionIdGenerator: undefined,
136 enableJsonResponse: true,
137 })
138 await mcp.connect(transport)
139 const response = await transport.handleRequest(
140 new Request(url, {
141 method: req.method,
142 headers: webHeaders(req),
143 body: await readBody(req),
144 }),
145 )
146 res.writeHead(response.status, Object.fromEntries(response.headers))
147 res.end(await response.text())
148 return
149 }
150 res.writeHead(404).end()
151 })()
152 })
153 await new Promise<void>((resolve) =>
154 server.listen(0, '127.0.0.1', () => resolve()),
155 )
156 const address = server.address()
157 base = `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}`
158 return {
159 url: `${base}/mcp`,
160 /** The `issuer` of the authorization server metadata. */
161 issuer: base,
162 seen,
163 revoke: (token: string) => valid.delete(token),
164 close: () =>
165 new Promise<void>((resolve) => {
166 server.closeAllConnections()
167 server.close(() => resolve())
168 }),
169 }