Skip to content

Commit df97084

Browse files
feat(mcp): implement resilience middleware pipeline
1 parent 80917d2 commit df97084

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import type { McpExecutionContext, McpMiddleware, McpMiddlewareNext } from './types'
2+
import type { McpToolResult } from '@/lib/mcp/types'
3+
4+
export class ResiliencePipeline {
5+
private middlewares: McpMiddleware[] = []
6+
7+
/**
8+
* Add a middleware to the pipeline chain.
9+
*/
10+
use(middleware: McpMiddleware): this {
11+
this.middlewares.push(middleware)
12+
return this
13+
}
14+
15+
/**
16+
* Execute the pipeline, processing the context through all middlewares,
17+
* and finally invoking the terminal handler.
18+
*/
19+
async execute(
20+
context: McpExecutionContext,
21+
finalHandler: McpMiddlewareNext
22+
): Promise<McpToolResult> {
23+
let index = -1
24+
25+
const dispatch = async (i: number): Promise<McpToolResult> => {
26+
if (i <= index) {
27+
throw new Error('next() called multiple times')
28+
}
29+
index = i
30+
31+
// If we reached the end of the middlewares, call the final handler
32+
if (i === this.middlewares.length) {
33+
return finalHandler(context)
34+
}
35+
36+
const middleware = this.middlewares[i]
37+
return middleware.execute(context, () => dispatch(i + 1))
38+
}
39+
40+
return dispatch(0)
41+
}
42+
}

0 commit comments

Comments
 (0)