Skip to content

Commit 7438f00

Browse files
committed
fix: mcp context proto
1 parent 22807f7 commit 7438f00

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

plugin/controller/lib/impl/mcp/MCPControllerRegister.ts

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -344,9 +344,21 @@ export class MCPControllerRegister implements ControllerRegister {
344344
this.app.logger.error('session %s error %o', transport.sessionId, error);
345345
};
346346
const messageFunc = transport.onmessage;
347+
const self = this;
347348
transport.onmessage = async (...args: [ JSONRPCMessage ]) => {
348-
await ctx.app.ctxStorage.run(ctx, async () => {
349-
await mw(ctx, async () => {
349+
// 这里需要 new 一个新的 ctx,否则 ContextProto 会未被初始化
350+
const socket = new Socket();
351+
const req = new IncomingMessage(socket);
352+
const res = new ServerResponse(req);
353+
req.method = 'POST';
354+
req.url = self.mcpConfig.sseInitPath;
355+
req.headers = {
356+
accept: 'application/json, text/event-stream',
357+
'content-type': 'application/json',
358+
};
359+
const newCtx = self.app.createContext(req, res) as unknown as Context;
360+
await ctx.app.ctxStorage.run(newCtx, async () => {
361+
await mw(newCtx, async () => {
350362
await messageFunc!(...args);
351363
});
352364
});

plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
ToolArgsSchema,
1515
} from '@eggjs/tegg';
1616
import z from 'zod';
17+
import { CommonService } from '../services/common';
1718

1819
export const PromptType = {
1920
name: z.string(),
@@ -32,6 +33,9 @@ export class McpController {
3233
@Inject()
3334
logger: Logger;
3435

36+
@Inject()
37+
commonService: CommonService;
38+
3539
@MCPPrompt()
3640
async foo(@PromptArgsSchema(PromptType) args: PromptArgs<typeof PromptType>): Promise<MCPPromptResponse> {
3741
this.logger.info('hello world');
@@ -50,6 +54,7 @@ export class McpController {
5054

5155
@MCPTool()
5256
async bar(@ToolArgsSchema(ToolType) args: ToolArgs<typeof ToolType>): Promise<MCPToolResponse> {
57+
await this.commonService.sayHello();
5358
return {
5459
content: [
5560
{
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import {
2+
Logger,
3+
ContextProto,
4+
Inject,
5+
} from '@eggjs/tegg';
6+
7+
@ContextProto()
8+
export class CommonService {
9+
10+
@Inject()
11+
logger: Logger;
12+
13+
async sayHello(): Promise<string> {
14+
this.logger.info('hello world');
15+
return 'hello world';
16+
}
17+
}

0 commit comments

Comments
 (0)