Skip to content

implement mcp logging #8834

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 1 commit into
base: master
Choose a base branch
from
Open
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
56 changes: 53 additions & 3 deletions src/mcp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import {
CallToolRequest,
CallToolRequestSchema,
CallToolResult,
ListToolsRequestSchema,
ListToolsResult,
LoggingLevel,
SetLevelRequestSchema,
ListToolsRequestSchema,
CallToolResult,
} from "@modelcontextprotocol/sdk/types.js";
import { checkFeatureActive, mcpError } from "./util.js";
import { ClientConfig, SERVER_FEATURES, ServerFeature } from "./types.js";
Expand All @@ -30,8 +32,19 @@

const cmd = new Command("experimental:mcp").before(requireAuth);

const orderedLogLevels = [
"debug",
"info",
"notice",
"warning",
"error",
"critical",
"alert",
"emergency",
] as const;

export class FirebaseMcpServer {
private _ready: boolean = false;

Check warning on line 47 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Type boolean trivially inferred from a boolean literal, remove type annotation
private _readyPromises: { resolve: () => void; reject: (err: unknown) => void }[] = [];
startupRoot?: string;
cachedProjectRoot?: string;
Expand All @@ -41,18 +54,29 @@
clientInfo?: { name?: string; version?: string };
emulatorHubClient?: EmulatorHubClient;

// logging spec:
// https://modelcontextprotocol.io/specification/2025-03-26/server/utilities/logging
currentLogLevel?: LoggingLevel;
// the api of logging from a consumers perspective looks like `server.logger.warn("my warning")`.
public readonly logger = Object.fromEntries(
orderedLogLevels.map((logLevel) => [
logLevel,
(message: unknown) => this.log(logLevel, message),
]),
) as Record<LoggingLevel, (message: unknown) => Promise<void>>;

constructor(options: { activeFeatures?: ServerFeature[]; projectRoot?: string }) {
this.activeFeatures = options.activeFeatures;
this.startupRoot = options.projectRoot || process.env.PROJECT_ROOT;
this.server = new Server({ name: "firebase", version: SERVER_VERSION });
this.server.registerCapabilities({ tools: { listChanged: true } });
this.server.registerCapabilities({ tools: { listChanged: true }, logging: {} });
this.server.setRequestHandler(ListToolsRequestSchema, this.mcpListTools.bind(this));
this.server.setRequestHandler(CallToolRequestSchema, this.mcpCallTool.bind(this));
this.server.oninitialized = async () => {

Check warning on line 75 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Promise-returning function provided to variable where a void return was expected
const clientInfo = this.server.getClientVersion();
this.clientInfo = clientInfo;
if (clientInfo?.name) {
trackGA4("mcp_client_connected", {

Check warning on line 79 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
mcp_client_name: clientInfo.name,
mcp_client_version: clientInfo.version,
});
Expand All @@ -64,28 +88,34 @@
this._readyPromises.pop()?.resolve();
}
};

this.server.setRequestHandler(SetLevelRequestSchema, async ({ params }) => {
this.currentLogLevel = params.level;
return {};
});

this.detectProjectRoot();

Check warning on line 97 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
this.detectActiveFeatures();

Check warning on line 98 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator
}

/** Wait until initialization has finished. */
ready() {

Check warning on line 102 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
if (this._ready) return Promise.resolve();
return new Promise((resolve, reject) => {
this._readyPromises.push({ resolve: resolve as () => void, reject });
});
}

private get clientConfigKey() {

Check warning on line 109 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
return `mcp.clientConfigs.${this.clientInfo?.name || "<unknown-client>"}:${this.startupRoot || process.cwd()}`;
}

getStoredClientConfig(): ClientConfig {
return configstore.get(this.clientConfigKey) || {};

Check warning on line 114 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe return of an `any` typed value
}

updateStoredClientConfig(update: Partial<ClientConfig>) {

Check warning on line 117 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Missing return type on function
const config = configstore.get(this.clientConfigKey) || {};

Check warning on line 118 in src/mcp/index.ts

View workflow job for this annotation

GitHub Actions / lint (20)

Unsafe assignment of an `any` value
const newConfig = { ...config, ...update };
configstore.set(this.clientConfigKey, newConfig);
return newConfig;
Expand Down Expand Up @@ -275,4 +305,24 @@
const transport = new StdioServerTransport();
await this.server.connect(transport);
}

private async log(level: LoggingLevel, message: unknown) {
let data = message;

// mcp protocol only takes jsons or it errors; for convienence, format
// a a string into a json.
if (typeof message === "string") {
data = { message };
}

if (!this.currentLogLevel) {
return;
}

if (orderedLogLevels.indexOf(this.currentLogLevel) > orderedLogLevels.indexOf(level)) {
return;
}

await this.server.sendLoggingMessage({ level, data });
}
}
Loading