Registry Mirror
Skip to content

File tree

‎packages/cloudflare/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,10 @@
6060
},
6161
"devDependencies": {
6262
"@cloudflare/vitest-plugin": "^1.5.0",
63+
"@modelcontextprotocol/server": "^2.4.0",
64+
"@orpc/mcp": "workspace:*",
65+
"@orpc/openapi": "workspace:*",
66+
"@orpc/server": "workspace:*",
6367
"@vitest/coverage-istanbul": "^4.1.11",
6468
"vitest": "^4.1.11",
6569
"wrangler": "^4.164.0"
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { sleep } from '@orpc/shared'
2+
import { exports } from 'cloudflare:workers'
3+
4+
type FetchHandler = (request: Request, env: Env, ctx: ExecutionContext) => Promise<Response>
5+
6+
let current: FetchHandler | undefined
7+
8+
/**
9+
* Sets the main Worker's fetch handler, so each test can run its own Worker
10+
* through `exports.default.fetch`, with every call a separate incoming request.
11+
*/
12+
export function setFetchHandler(handler: FetchHandler | undefined): void {
13+
current = handler
14+
}
15+
16+
export function handleFetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
17+
return current!(request, env, ctx)
18+
}
19+
20+
/**
21+
* Sends an incoming request to the main Worker and returns the response text.
22+
*/
23+
export async function fetchText(path: string, init?: RequestInit): Promise<string> {
24+
const response = await exports.default.fetch(`http://x${path}`, init)
25+
26+
return response.text()
27+
}
28+
29+
/**
30+
* Races with a timer of the current request, so a promise that never settles reports `'timeout'`.
31+
*/
32+
export function withTimeout<T>(promise: Promise<T>, ms = 1000): Promise<T | 'timeout'> {
33+
return Promise.race([promise, sleep(ms).then(() => 'timeout' as const)])
34+
}

‎packages/cloudflare/tests/__shared__/main.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { experimental_DurableLockObject as DurableLockObject } from '../../src/lock-object'
22
import { DurablePublisherObject } from '../../src/publisher-object'
3+
import { handleFetch } from './fetch-handler'
34

45
export class PublisherDO extends DurablePublisherObject {}
56

@@ -16,3 +17,7 @@ export class PublisherResume3sDO extends DurablePublisherObject {
1617
}
1718

1819
export class LockDO extends DurableLockObject {}
20+
21+
export default {
22+
fetch: handleFetch,
23+
} satisfies ExportedHandler<Env>
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import { openapi } from '@orpc/openapi'
2+
import { OpenAPIHandler } from '@orpc/openapi/fetch'
3+
import { os } from '@orpc/server'
4+
import { RPCHandler } from '@orpc/server/fetch'
5+
import { sleep } from '@orpc/shared'
6+
import { describe, expect, it } from 'vitest'
7+
8+
import { fetchText, setFetchHandler, withTimeout } from './__shared__/fetch-handler'
9+
10+
const ping = os.meta(openapi({ method: 'POST', path: '/nested/ping' })).handler(() => 'pong')
11+
12+
describe.each([
13+
{ name: 'RPCHandler', Handler: RPCHandler, output: '{"json":"pong"}' },
14+
{ name: 'OpenAPIHandler', Handler: OpenAPIHandler, output: '"pong"' },
15+
])('lazy router with $name', ({ Handler, output }) => {
16+
/**
17+
* Kept outside the fetch handler like a real Worker. The loader's first call waits on
18+
* a timer of the calling request, so it never settles once that request ends.
19+
*/
20+
function setup() {
21+
let loads = 0
22+
23+
const handler = new Handler({
24+
nested: os.lazy(async () => {
25+
if (++loads === 1) {
26+
await sleep(50)
27+
}
28+
29+
return { default: { ping } }
30+
}),
31+
})
32+
33+
setFetchHandler(async (request) => {
34+
const handling = handler.handle(request, { prefix: '/api', context: {} })
35+
36+
if (new URL(request.url).searchParams.has('early')) {
37+
handling.catch(() => {})
38+
await sleep(20)
39+
return new Response('ended early')
40+
}
41+
42+
const result = await withTimeout(handling)
43+
44+
if (result === 'timeout' || !result.matched) {
45+
return new Response(result === 'timeout' ? result : 'not matched')
46+
}
47+
48+
return new Response(await result.response.text())
49+
})
50+
51+
return { loads: () => loads }
52+
}
53+
54+
const call = (search = '') =>
55+
fetchText(`/api/nested/ping${search}`, {
56+
method: 'POST',
57+
headers: { 'content-type': 'application/json' },
58+
})
59+
60+
it('serves a request sent after the loading request ended', async () => {
61+
const { loads } = setup()
62+
63+
expect(await call('?early')).toBe('ended early')
64+
expect(loads()).toBe(1)
65+
66+
expect(await call()).toBe(output)
67+
expect(loads()).toBe(2)
68+
69+
expect(await call()).toBe(output)
70+
expect(loads()).toBe(2)
71+
})
72+
73+
it('serves concurrent requests after the loading request ended', async () => {
74+
const { loads } = setup()
75+
76+
expect(await call('?early')).toBe('ended early')
77+
78+
expect(await Promise.all([call(), call()])).toEqual([output, output])
79+
// each loads unless the other already indexed it
80+
const loadsAfter = loads()
81+
expect(loadsAfter).toBeGreaterThanOrEqual(2)
82+
expect(loadsAfter).toBeLessThanOrEqual(3)
83+
84+
expect(await call()).toBe(output)
85+
expect(loads()).toBe(loadsAfter)
86+
})
87+
})
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server'
2+
import { McpRegistrar } from '@orpc/mcp'
3+
import { os } from '@orpc/server'
4+
import { promiseWithResolvers, sleep } from '@orpc/shared'
5+
import { describe, expect, it } from 'vitest'
6+
7+
import { fetchText, setFetchHandler, withTimeout } from './__shared__/fetch-handler'
8+
9+
/**
10+
* A lazy router whose first load waits on a timer created in the calling request,
11+
* so it never settles once that request ends, while later loads resolve at once.
12+
*/
13+
function createLazyRouter() {
14+
let loads = 0
15+
const firstLoadStarted = promiseWithResolvers<void>()
16+
17+
const router = {
18+
planet: os.lazy(async () => {
19+
if (++loads === 1) {
20+
firstLoadStarted.resolve()
21+
await sleep(10)
22+
}
23+
24+
return { default: { find: os.handler(() => ({ name: 'Earth' })) } }
25+
}),
26+
}
27+
28+
return { router, firstLoadStarted: firstLoadStarted.promise, loads: () => loads }
29+
}
30+
31+
function createServer() {
32+
return new McpServer({ name: 'test-server', version: '1.0.0' })
33+
}
34+
35+
describe('mcpRegistrar with a lazy router on Workers', () => {
36+
it('registers tools in a later request after the request that started the load ends early', async () => {
37+
const { router, firstLoadStarted, loads } = createLazyRouter()
38+
const registrar = new McpRegistrar(router)
39+
40+
setFetchHandler(async (request) => {
41+
if (new URL(request.url).pathname === '/a') {
42+
// ends once the load starts, without awaiting it, like a disconnected client
43+
registrar.register(createServer()).catch(() => {})
44+
return new Response(await withTimeout(firstLoadStarted.then(() => 'started')))
45+
}
46+
47+
const result = await withTimeout(registrar.register(createServer()))
48+
return new Response(result === 'timeout' ? result : Object.keys(result.tools).join(','))
49+
})
50+
51+
expect(await fetchText('/a')).toBe('started')
52+
expect(await fetchText('/b')).toBe('planet_find')
53+
expect(loads()).toBe(2)
54+
expect(await fetchText('/b')).toBe('planet_find')
55+
expect(loads()).toBe(2)
56+
})
57+
58+
it('calls a tool through createMcpHandler in a later request after the request that started the load ends early', async () => {
59+
const { router, firstLoadStarted } = createLazyRouter()
60+
const registrar = new McpRegistrar(router)
61+
const handler = createMcpHandler(async () => {
62+
const server = createServer()
63+
await registrar.register(server)
64+
return server
65+
})
66+
67+
const toolCall = () =>
68+
new Request('http://x/mcp', {
69+
method: 'POST',
70+
headers: {
71+
'content-type': 'application/json',
72+
'accept': 'application/json, text/event-stream',
73+
},
74+
body: JSON.stringify({
75+
jsonrpc: '2.0',
76+
id: 1,
77+
method: 'tools/call',
78+
params: { name: 'planet_find', arguments: {} },
79+
}),
80+
})
81+
82+
setFetchHandler(async (request) => {
83+
if (new URL(request.url).pathname === '/a') {
84+
handler.fetch(toolCall()).catch(() => {})
85+
return new Response(await withTimeout(firstLoadStarted.then(() => 'started')))
86+
}
87+
88+
const result = await withTimeout(handler.fetch(toolCall()).then((r) => r.text()))
89+
return new Response(result)
90+
})
91+
92+
try {
93+
expect(await fetchText('/a')).toBe('started')
94+
95+
const text = await fetchText('/b')
96+
// a stateless legacy request is answered over SSE
97+
expect(JSON.parse(text.match(/^data: (.*)$/m)![1]!)).toEqual({
98+
jsonrpc: '2.0',
99+
id: 1,
100+
result: {
101+
content: [{ type: 'text', text: '{"name":"Earth"}' }],
102+
structuredContent: { name: 'Earth' },
103+
},
104+
})
105+
} finally {
106+
await handler.close()
107+
}
108+
})
109+
})

‎packages/mcp/src/registrar.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { openapi, OpenAPISerializer } from '@orpc/openapi'
99
import { implement, os } from '@orpc/server'
1010
import type { ResponseHeadersHandlerPluginContext } from '@orpc/server/plugins'
1111
import { ResponseHeadersHandlerPlugin } from '@orpc/server/plugins'
12+
import { promiseWithResolvers } from '@orpc/shared'
1213
import { ZodToJsonSchemaConverter } from '@orpc/zod'
1314
import { z } from 'zod'
1415

@@ -1371,6 +1372,28 @@ describe('mcpRegistrar', () => {
13711372
expect(loader).toHaveBeenCalledTimes(2)
13721373
})
13731374

1375+
it('resolves routes while another call is still loading, and drops the slower load', async () => {
1376+
const first = os.handler(() => 'first')
1377+
const second = os.handler(() => 'second')
1378+
const firstLoad = promiseWithResolvers<{ default: any }>()
1379+
const loader = vi
1380+
.fn()
1381+
.mockReturnValueOnce(firstLoad.promise)
1382+
.mockResolvedValueOnce({ default: { ping: second } })
1383+
1384+
const registrar = new McpRegistrar({ planet: os.lazy(loader) })
1385+
const matcher = (registrar as any).matcher
1386+
1387+
const slow = matcher.resolveRoutes()
1388+
const routes = await matcher.resolveRoutes()
1389+
expect(routes.get('/planet/ping').procedure['~orpc'].handler).toBe(second['~orpc'].handler)
1390+
1391+
firstLoad.resolve({ default: { ping: first } })
1392+
1393+
await expect(slow).resolves.toBe(routes)
1394+
await expect(matcher.resolveRoutes()).resolves.toBe(routes)
1395+
})
1396+
13741397
it('registers on multiple servers', async () => {
13751398
const registrar = new McpRegistrar(router)
13761399

‎packages/mcp/src/registrar.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -330,24 +330,27 @@ export class McpRegistrar<T extends AnyRouter> {
330330
* Lazy routers and contract-first implementations are loaded on first use and reused afterward.
331331
*/
332332
class McpMatcher {
333-
private routes: Promise<Map<`/${string}`, McpRoute>> | undefined
333+
private routes: Map<`/${string}`, McpRoute> | undefined
334334

335335
constructor(
336336
private readonly router: AnyRouter,
337337
private readonly converter: Pick<JsonSchemaConverter, 'convert'>,
338338
private readonly filter: McpRegistrarOptions<any>['filter'],
339339
) {}
340340

341-
resolveRoutes(): Promise<Map<`/${string}`, McpRoute>> {
342-
return (this.routes ??= this.loadRoutes().catch((error) => {
343-
// retry on the next call, such as when a lazy router failed to load
344-
this.routes = undefined
345-
throw error
346-
}))
341+
/** Not shared across calls: on Cloudflare Workers, a promise never settles once its request ends. */
342+
async resolveRoutes(): Promise<Map<`/${string}`, McpRoute>> {
343+
if (this.routes !== undefined) {
344+
return this.routes
345+
}
346+
347+
const routes = await this.loadRoutes()
348+
349+
return (this.routes ??= routes)
347350
}
348351

349352
async match(pathname: `/${string}`): Promise<McpRoute | undefined> {
350-
return (await this.resolveRoutes()).get(pathname)
353+
return (this.routes ?? (await this.resolveRoutes())).get(pathname)
351354
}
352355

353356
private async loadRoutes(): Promise<Map<`/${string}`, McpRoute>> {

0 commit comments

Comments
 (0)