Skip to content

Automatic handling of logging level #882

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
28 changes: 14 additions & 14 deletions src/examples/server/jsonResponseStreamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,27 @@ const getServer = () => {
{
name: z.string().describe('Name to greet'),
},
async ({ name }, { sendNotification }): Promise<CallToolResult> => {
async ({ name }, extra): Promise<CallToolResult> => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

await sendNotification({
method: "notifications/message",
params: { level: "debug", data: `Starting multi-greet for ${name}` }
});
await server.sendLoggingMessage({
level: "debug",
data: `Starting multi-greet for ${name}`
}, extra.sessionId);

await sleep(1000); // Wait 1 second before first greeting

await sendNotification({
method: "notifications/message",
params: { level: "info", data: `Sending first greeting to ${name}` }
});
await server.sendLoggingMessage({
level: "info",
data: `Sending first greeting to ${name}`
}, extra.sessionId);

await sleep(1000); // Wait another second before second greeting

await sendNotification({
method: "notifications/message",
params: { level: "info", data: `Sending second greeting to ${name}` }
});
await server.sendLoggingMessage({
level: "info",
data: `Sending second greeting to ${name}`
}, extra.sessionId);

return {
content: [
Expand Down Expand Up @@ -170,4 +170,4 @@ app.listen(PORT, (error) => {
process.on('SIGINT', async () => {
console.log('Shutting down server...');
process.exit(0);
});
});
28 changes: 11 additions & 17 deletions src/examples/server/simpleSseServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ import { z } from 'zod';
import { CallToolResult } from '../../types.js';

/**
* This example server demonstrates the deprecated HTTP+SSE transport
* This example server demonstrates the deprecated HTTP+SSE transport
* (protocol version 2024-11-05). It mainly used for testing backward compatible clients.
*
*
* The server exposes two endpoints:
* - /mcp: For establishing the SSE stream (GET)
* - /messages: For receiving client messages (POST)
*
*
*/

// Create an MCP server instance
Expand All @@ -28,32 +28,26 @@ const getServer = () => {
interval: z.number().describe('Interval in milliseconds between notifications').default(1000),
count: z.number().describe('Number of notifications to send').default(10),
},
async ({ interval, count }, { sendNotification }): Promise<CallToolResult> => {
async ({ interval, count }, extra): Promise<CallToolResult> => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
let counter = 0;

// Send the initial notification
await sendNotification({
method: "notifications/message",
params: {
level: "info",
data: `Starting notification stream with ${count} messages every ${interval}ms`
}
});
await server.sendLoggingMessage({
level: "info",
data: `Starting notification stream with ${count} messages every ${interval}ms`
}, extra.sessionId);

// Send periodic notifications
while (counter < count) {
counter++;
await sleep(interval);

try {
await sendNotification({
method: "notifications/message",
params: {
await server.sendLoggingMessage({
level: "info",
data: `Notification #${counter} at ${new Date().toISOString()}`
}
});
}, extra.sessionId);
}
catch (error) {
console.error("Error sending notification:", error);
Expand Down Expand Up @@ -169,4 +163,4 @@ process.on('SIGINT', async () => {
}
console.log('Server shutdown complete');
process.exit(0);
});
});
15 changes: 6 additions & 9 deletions src/examples/server/simpleStatelessStreamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,17 @@ const getServer = () => {
interval: z.number().describe('Interval in milliseconds between notifications').default(100),
count: z.number().describe('Number of notifications to send (0 for 100)').default(10),
},
async ({ interval, count }, { sendNotification }): Promise<CallToolResult> => {
async ({ interval, count }, extra): Promise<CallToolResult> => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
let counter = 0;

while (count === 0 || counter < count) {
counter++;
try {
await sendNotification({
method: "notifications/message",
params: {
level: "info",
data: `Periodic notification #${counter} at ${new Date().toISOString()}`
}
});
await server.sendLoggingMessage({
level: "info",
data: `Periodic notification #${counter} at ${new Date().toISOString()}`
}, extra.sessionId);
}
catch (error) {
console.error("Error sending notification:", error);
Expand Down Expand Up @@ -170,4 +167,4 @@ app.listen(PORT, (error) => {
process.on('SIGINT', async () => {
console.log('Shutting down server...');
process.exit(0);
});
});
39 changes: 18 additions & 21 deletions src/examples/server/simpleStreamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,27 @@ const getServer = () => {
readOnlyHint: true,
openWorldHint: false
},
async ({ name }, { sendNotification }): Promise<CallToolResult> => {
async ({ name }, extra): Promise<CallToolResult> => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));

await sendNotification({
method: "notifications/message",
params: { level: "debug", data: `Starting multi-greet for ${name}` }
});
await server.sendLoggingMessage({
level: "debug",
data: `Starting multi-greet for ${name}`
}, extra.sessionId);

await sleep(1000); // Wait 1 second before first greeting

await sendNotification({
method: "notifications/message",
params: { level: "info", data: `Sending first greeting to ${name}` }
});
await server.sendLoggingMessage({
level: "info",
data: `Sending first greeting to ${name}`
}, extra.sessionId);

await sleep(1000); // Wait another second before second greeting

await sendNotification({
method: "notifications/message",
params: { level: "info", data: `Sending second greeting to ${name}` }
});
await server.sendLoggingMessage({
level: "info",
data: `Sending second greeting to ${name}`
}, extra.sessionId);

return {
content: [
Expand Down Expand Up @@ -273,20 +273,17 @@ const getServer = () => {
interval: z.number().describe('Interval in milliseconds between notifications').default(100),
count: z.number().describe('Number of notifications to send (0 for 100)').default(50),
},
async ({ interval, count }, { sendNotification }): Promise<CallToolResult> => {
async ({ interval, count }, extra): Promise<CallToolResult> => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
let counter = 0;

while (count === 0 || counter < count) {
counter++;
try {
await sendNotification({
method: "notifications/message",
params: {
level: "info",
data: `Periodic notification #${counter} at ${new Date().toISOString()}`
}
});
await server.sendLoggingMessage( {
level: "info",
data: `Periodic notification #${counter} at ${new Date().toISOString()}`
}, extra.sessionId);
}
catch (error) {
console.error("Error sending notification:", error);
Expand Down
17 changes: 7 additions & 10 deletions src/examples/server/sseAndStreamableHttpCompatibleServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import cors from 'cors';
* This example server demonstrates backwards compatibility with both:
* 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05)
* 2. The Streamable HTTP transport (protocol version 2025-03-26)
*
*
* It maintains a single MCP server instance but exposes two transport options:
* - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE)
* - /sse: The deprecated SSE endpoint for older clients (GET to establish stream)
Expand All @@ -33,20 +33,17 @@ const getServer = () => {
interval: z.number().describe('Interval in milliseconds between notifications').default(100),
count: z.number().describe('Number of notifications to send (0 for 100)').default(50),
},
async ({ interval, count }, { sendNotification }): Promise<CallToolResult> => {
async ({ interval, count }, extra): Promise<CallToolResult> => {
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
let counter = 0;

while (count === 0 || counter < count) {
counter++;
try {
await sendNotification({
method: "notifications/message",
params: {
level: "info",
data: `Periodic notification #${counter} at ${new Date().toISOString()}`
}
});
await server.sendLoggingMessage({
level: "info",
data: `Periodic notification #${counter} at ${new Date().toISOString()}`
}, extra.sessionId);
}
catch (error) {
console.error("Error sending notification:", error);
Expand Down Expand Up @@ -254,4 +251,4 @@ process.on('SIGINT', async () => {
}
console.log('Server shutdown complete');
process.exit(0);
});
});
50 changes: 45 additions & 5 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import {
ServerRequest,
ServerResult,
SUPPORTED_PROTOCOL_VERSIONS,
LoggingLevel, SetLevelRequestSchema,
} from "../types.js";
import Ajv from "ajv";

Expand Down Expand Up @@ -108,8 +109,37 @@ export class Server<
this.setNotificationHandler(InitializedNotificationSchema, () =>
this.oninitialized?.(),
);

if (this._capabilities.logging) {
this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {
const transportSessionId: string | undefined = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] as string || undefined;
const { level } = request.params;
if (transportSessionId && this._levelNames.some(l => l === level)) {
this._loggingLevels.set(transportSessionId, level);
}
return {};
})
}
}

private _loggingLevels = new Map<string, LoggingLevel>();
private _levelNames = [
"debug",
"info",
"notice",
"warning",
"error",
"critical",
"alert",
"emergency",
];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like we're duplicating information that should already be available as an enum from LoggingLevelSchema?

export const LoggingLevelSchema = z.enum([

Is there a way we can use that directly without creating a duplicated _levelNames array and iterating through it each time?

For example:

// Create a severity map from the LoggingLevelSchema once
private readonly LOG_LEVEL_SEVERITY = new Map(
  LoggingLevelSchema.options.map((level, index) => [level, index])
);

private isMessageIgnored = (level: LoggingLevel, sessionId: string): boolean => {
  const currentLevel = this._loggingLevels.get(sessionId);
  if (!currentLevel) return false;

  return this.LOG_LEVEL_SEVERITY.get(level)! < this.LOG_LEVEL_SEVERITY.get(currentLevel)!;
};

// In the setLevel handler:
const parseResult = LoggingLevelSchema.safeParse(level);
if (transportSessionId && parseResult.success) {
  this._loggingLevels.set(transportSessionId, parseResult.data);
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@felixweinberger I had this concern as well, I just opted for the straightforward implementation. Thanks for calling it out.

I've made the changes, and tested locally. Here, I'm using the example you can run with npm run examples:simple-server:w

log-levels.mov


private isMessageIgnored = (level: LoggingLevel, sessionId: string): boolean => {
const currentLevel = this._levelNames.findIndex((l) => this._loggingLevels.get(sessionId) === l);
const messageLevel = this._levelNames.findIndex((l) => level === l);
return messageLevel < currentLevel;
};

/**
* Registers new capabilities. This can only be called before connecting to a transport.
*
Expand All @@ -121,7 +151,6 @@ export class Server<
"Cannot register capabilities after connecting to transport",
);
}

this._capabilities = mergeCapabilities(this._capabilities, capabilities);
}

Expand Down Expand Up @@ -324,10 +353,10 @@ export class Server<
if (result.action === "accept" && result.content) {
try {
const ajv = new Ajv();

const validate = ajv.compile(params.requestedSchema);
const isValid = validate(result.content);

if (!isValid) {
throw new McpError(
ErrorCode.InvalidParams,
Expand Down Expand Up @@ -359,8 +388,19 @@ export class Server<
);
}

async sendLoggingMessage(params: LoggingMessageNotification["params"]) {
return this.notification({ method: "notifications/message", params });
/**
* Sends a logging message to the client, if connected.
* Note: You only need to send the parameters object, not the entire JSON RPC message
* @see LoggingMessageNotification
* @param params
* @param sessionId optional for stateless and backward compatibility
*/
async sendLoggingMessage(params: LoggingMessageNotification["params"], sessionId?: string) {
if (this._capabilities.logging) {
if (!sessionId || !this.isMessageIgnored(params.level, sessionId)) {
return this.notification({method: "notifications/message", params})
}
}
}

async sendResourceUpdated(params: ResourceUpdatedNotification["params"]) {
Expand Down
17 changes: 14 additions & 3 deletions src/server/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import {
ServerRequest,
ServerNotification,
ToolAnnotations,
LoggingMessageNotification,
} from "../types.js";
import { Completable, CompletableDef } from "./completable.js";
import { UriTemplate, Variables } from "../shared/uriTemplate.js";
Expand Down Expand Up @@ -822,7 +823,7 @@ export class McpServer {
/**
* Registers a tool taking either a parameter schema for validation or annotations for additional metadata.
* This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases.
*
*
* Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate
* between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types.
*/
Expand All @@ -834,9 +835,9 @@ export class McpServer {

/**
* Registers a tool `name` (with a description) taking either parameter schema or annotations.
* This unified overload handles both `tool(name, description, paramsSchema, cb)` and
* This unified overload handles both `tool(name, description, paramsSchema, cb)` and
* `tool(name, description, annotations, cb)` cases.
*
*
* Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate
* between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types.
*/
Expand Down Expand Up @@ -1047,6 +1048,16 @@ export class McpServer {
return this.server.transport !== undefined
}

/**
* Sends a logging message to the client, if connected.
* Note: You only need to send the parameters object, not the entire JSON RPC message
* @see LoggingMessageNotification
* @param params
* @param sessionId optional for stateless and backward compatibility
*/
async sendLoggingMessage(params: LoggingMessageNotification["params"], sessionId?: string) {
return this.server.sendLoggingMessage(params, sessionId);
}
/**
* Sends a resource list changed event to the client, if connected.
*/
Expand Down