Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/green-dryers-film.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@modelcontextprotocol/server": patch
---

fix(server): reject requests before initialization
16 changes: 14 additions & 2 deletions packages/server/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export class Server extends Protocol<ServerContext> {
private _capabilities: ServerCapabilities;
private _instructions?: string;
private _jsonSchemaValidator: jsonSchemaValidator;
private _receivedInitialize = false;

/**
* Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification).
Expand Down Expand Up @@ -184,8 +185,19 @@ export class Server extends Protocol<ServerContext> {
method: string,
handler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result>
): (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result> {
const lifecycleHandler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result> = async (request, ctx) => {
if (!ctx.http && ctx.sessionId === undefined && !this._receivedInitialize && method !== 'initialize' && method !== 'ping') {
throw new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Server not initialized');
}
const result = await handler(request, ctx);
if (method === 'initialize') {
this._receivedInitialize = true;
}
return result;
};

if (method !== 'tools/call') {
return handler;
return lifecycleHandler;
}
return async (request, ctx) => {
const validatedRequest = parseSchema(CallToolRequestSchema, request);
Expand All @@ -195,7 +207,7 @@ export class Server extends Protocol<ServerContext> {
throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);
}

const result = await handler(request, ctx);
const result = await lifecycleHandler(request, ctx);

const validationResult = parseSchema(CallToolResultSchema, result);
if (!validationResult.success) {
Expand Down
68 changes: 68 additions & 0 deletions packages/server/test/server/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
InMemoryTransport,
isJSONRPCResultResponse,
LATEST_PROTOCOL_VERSION,
ProtocolErrorCode,
SUPPORTED_PROTOCOL_VERSIONS
} from '@modelcontextprotocol/core';
import { Server } from '../../src/server/server.js';
Expand Down Expand Up @@ -84,6 +85,73 @@ describe('Server', () => {

await server.close();
});

it('rejects requests before initialize', async () => {
const server = new Server({ name: 'test', version: '1.0.0' }, { capabilities: { tools: {} } });

server.setRequestHandler('tools/list', async () => ({ tools: [] }));

const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);

const responses: JSONRPCMessage[] = [];
clientTransport.onmessage = message => responses.push(message);
await clientTransport.start();

await clientTransport.send({
jsonrpc: '2.0',
method: 'notifications/initialized'
} as JSONRPCMessage);

await clientTransport.send({
jsonrpc: '2.0',
id: 1,
method: 'tools/list',
params: {}
} as JSONRPCMessage);

await vi.waitFor(() => expect(responses.some(message => 'id' in message && message.id === 1)).toBe(true));

const rejected = responses.find(message => 'id' in message && message.id === 1);
expect(rejected).toMatchObject({
error: {
code: ProtocolErrorCode.InvalidRequest,
message: 'Server not initialized'
}
});

await clientTransport.send({
jsonrpc: '2.0',
id: 2,
method: 'initialize',
params: {
protocolVersion: LATEST_PROTOCOL_VERSION,
capabilities: {},
clientInfo: { name: 'test-client', version: '1.0.0' }
}
} as JSONRPCMessage);
await vi.waitFor(() => expect(responses.some(message => 'id' in message && message.id === 2)).toBe(true));

await clientTransport.send({
jsonrpc: '2.0',
method: 'notifications/initialized'
} as JSONRPCMessage);

await clientTransport.send({
jsonrpc: '2.0',
id: 3,
method: 'tools/list',
params: {}
} as JSONRPCMessage);

await vi.waitFor(() => expect(responses.some(message => 'id' in message && message.id === 3)).toBe(true));

expect(responses.find(message => 'id' in message && message.id === 3)).toMatchObject({
result: { tools: [] }
});

await server.close();
});
});

describe('getNegotiatedProtocolVersion', () => {
Expand Down
Loading