Skip to content

Commit 2ada652

Browse files
feat: add injectable SDK logger (#2370)
Co-authored-by: Konstantin Konstantinov <KKonstantinov@users.noreply.github.com>
1 parent 350f916 commit 2ada652

23 files changed

Lines changed: 734 additions & 56 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@modelcontextprotocol/core-internal': minor
3+
'@modelcontextprotocol/client': minor
4+
'@modelcontextprotocol/server': minor
5+
---
6+
7+
Add a `logger` option to `Client`, `McpServer`, `createMcpHandler` and the built-in OAuth providers such as `ClientCredentialsProvider`, and an optional `sdkLogger` property to `OAuthClientProvider`, so SDK diagnostics can be routed through user-provided logging. Omitting them keeps the current `console` output.

‎docs/clients/machine-auth.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ await client.connect(transport);
2929

3030
`expectedIssuer` is the `issuer` of the authorization server the credential was registered with. If discovery resolves a different issuer, the SDK throws `AuthorizationServerMismatchError` instead of sending the secret. `PrivateKeyJwtProvider` and `CrossAppAccessProvider` below take it too; omitting it is deprecated, and the credential then goes to whichever authorization server the MCP server advertises.
3131

32+
Every built-in provider also takes `logger`, a console-compatible `SdkLogger` for the warnings the SDK prints about it, such as that deprecation. It defaults to `console`.
33+
3234
## Bring your own bearer token
3335

3436
When something outside the SDK already owns the token — an API key, a gateway, a platform secret store — implement `AuthProvider` with only `token()`.

‎docs/clients/oauth.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,10 @@ The SDK calls the `save*` methods as the flow produces values and reads them bac
101101
When the requested scope includes `offline_access`, the SDK adds `prompt=consent` to the authorization URL. Set `skipOfflineAccessConsentPrompt = true` on the provider to omit it when consent is already granted out of band, such as a Microsoft Entra ID tenant with admin consent and user consent disabled.
102102
:::
103103

104+
::: tip
105+
`auth()` prints warnings while it runs, for example when a stored credential has no `issuer` stamp or a token refresh fails. Set `sdkLogger` on the provider to route them somewhere other than `console`. It takes the same console-compatible `SdkLogger` as `Client`'s `logger` option; a `logger` property your provider class already has is left alone.
106+
:::
107+
104108
## Finish the flow from the callback
105109

106110
The authorization server redirects the end user to `redirectUrl` with `code` and `state` in the query. Compare `state`, hand the whole query to `finishAuth`, and reconnect.

‎docs/servers/logging-progress-cancellation.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,25 @@ Only the result comes back:
7171

7272
`progress` must increase on every notification for the same token; `total` and `message` are optional.
7373

74+
## Route SDK diagnostics
75+
76+
Pass `logger` to `McpServer` to route the warnings and debug messages the SDK prints locally. On a stdio server, send every level to stderr: the server's stdout carries only MCP messages.
77+
78+
```ts source="../../examples/guides/servers/logging-progress-cancellation.examples.ts#McpServer_logger_stderr"
79+
const stderrLogger = {
80+
debug: (...args: unknown[]) => console.error('[debug]', ...args),
81+
warn: (...args: unknown[]) => console.error('[warn]', ...args)
82+
};
83+
84+
const diagnosticServer = new McpServer({ name: 'file-processor', version: '1.0.0' }, { logger: stderrLogger });
85+
```
86+
87+
`Client` and `createMcpHandler` take the same option. The low-level `Server` has no diagnostics of its own, so it does not take one. The SDK logs at two levels, `debug` and `warn`. Both methods are optional, and an omitted one discards diagnostics at that level. The default is `console`, and a logger that throws is ignored.
88+
89+
The client's OAuth helpers run outside a `Client`, so they read the logger from the auth provider instead: set `sdkLogger` on your `OAuthClientProvider`, or pass `logger` to a built-in provider such as `ClientCredentialsProvider`.
90+
91+
This logger stays local to the process. It does not send MCP `notifications/message`; use `ctx.mcpReq.log` for that deprecated protocol feature.
92+
7493
## Log to the client
7594

7695
::: warning Deprecated — SEP-2577
@@ -221,6 +240,7 @@ Resolve an identifier against a fixed list, as `fetch-source` does. A tool that
221240

222241
- Every handler receives a context as its second argument; the request-scoped helpers live on `ctx.mcpReq`.
223242
- `ctx.mcpReq.notify` sends `notifications/progress` when the request carried a `progressToken`; `progress` must increase on each one.
243+
- The `logger` option routes local SDK diagnostics; it is separate from MCP protocol logging.
224244
- `ctx.mcpReq.log(level, data)` sends `notifications/message` once the `logging` capability is declared; MCP logging is deprecated (SEP-2577).
225245
- Declaring `logging` also installs `logging/setLevel`; after `client.setLoggingLevel(level)` the SDK drops messages below that level for the session.
226246
- `ctx.mcpReq.signal` aborts on cancellation and disconnect — check it in long loops and forward it to your own I/O.

‎examples/guides/servers/logging-progress-cancellation.examples.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,17 @@ import * as z from 'zod/v4';
2020
const server = new McpServer({ name: 'file-processor', version: '1.0.0' }, { capabilities: { logging: {} } });
2121
//#endregion logging_capability
2222

23+
// "Route SDK diagnostics" — keep local SDK output off the stdio protocol channel.
24+
//#region McpServer_logger_stderr
25+
const stderrLogger = {
26+
debug: (...args: unknown[]) => console.error('[debug]', ...args),
27+
warn: (...args: unknown[]) => console.error('[warn]', ...args)
28+
};
29+
30+
const diagnosticServer = new McpServer({ name: 'file-processor', version: '1.0.0' }, { logger: stderrLogger });
31+
//#endregion McpServer_logger_stderr
32+
void diagnosticServer;
33+
2334
// "Report progress from a handler" — the page's lead block.
2435
//#region registerTool_progress
2536
server.registerTool(

‎packages/client/src/client/auth.ts‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,15 @@ import type {
99
OAuthMetadata,
1010
OAuthProtectedResourceMetadata,
1111
OAuthTokens,
12+
SdkLogger,
1213
StoredOAuthClientInformation,
1314
StoredOAuthTokens
1415
} from '@modelcontextprotocol/core-internal';
1516
import {
1617
brandedHasInstance,
1718
checkResourceAllowed,
1819
fetchWithinOrigin,
20+
guardLogger,
1921
LATEST_PROTOCOL_VERSION,
2022
OAuthClientInformationFullSchema,
2123
OAuthError,
@@ -119,7 +121,7 @@ export interface OAuthClientInformationContext {
119121
* as `undefined`, so a credential issued by one authorization server is never reused
120122
* at another — the flow falls through to re-registration / re-authorization exactly
121123
* as if nothing were stored. An unstamped value (legacy provider or pre-SEP-2352
122-
* storage) is returned as-is with a `console.warn`; {@linkcode auth} writes the
124+
* storage) is returned as-is with a warning; {@linkcode auth} writes the
123125
* stamp back on first use so the window closes after one call.
124126
*
125127
* {@linkcode auth} stamps every value it writes via `saveTokens` / `saveClientInformation`,
@@ -130,18 +132,19 @@ export interface OAuthClientInformationContext {
130132
* @param opts.canPersistStamp - When `false`, suppresses the unstamped-credential
131133
* warning: the caller cannot back-stamp (no `saveClientInformation`), so the
132134
* "binding on first use" claim would be false and would fire on every call.
135+
* @param opts.logger - Where the unstamped-credential warning goes. Defaults to `console`.
133136
*/
134137
export function discardIfIssuerMismatch<T extends { issuer?: string }>(
135138
stored: T | null | undefined,
136139
issuer: string,
137-
opts?: { canPersistStamp?: boolean }
140+
opts?: { canPersistStamp?: boolean; logger?: SdkLogger }
138141
): T | undefined {
139142
// Nothing stored (`null` from a `JSON.parse(storage.getItem(...))`-style getter included).
140143
if (!stored) return undefined;
141144
// A stamp that is not a string (raw storage) counts as no stamp.
142145
if (typeof stored.issuer !== 'string') {
143146
if (opts?.canPersistStamp !== false) {
144-
console.warn(
147+
guardLogger(opts?.logger).warn?.(
145148
`[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or ` +
146149
`provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ` +
147150
`ensure your provider round-trips the issuer field.`
@@ -271,6 +274,15 @@ export interface OAuthClientProvider {
271274
*/
272275
skipOfflineAccessConsentPrompt?: boolean;
273276

277+
/**
278+
* Console-compatible sink for the warnings {@linkcode auth} prints while it runs: unstamped
279+
* stored credentials, a missing `discoveryState()`, a failed token refresh and discarded
280+
* credentials. Omitted methods discard diagnostics at that level.
281+
*
282+
* @default console
283+
*/
284+
sdkLogger?: SdkLogger;
285+
274286
/**
275287
* Metadata about this OAuth client.
276288
*/
@@ -1077,7 +1089,9 @@ function warnCredentialInvalidation(provider: OAuthClientProvider, error: OAuthE
10771089
// JSON-stringify the AS-supplied values so attacker-supplied control characters cannot
10781090
// forge log lines — the authorization server is resolved from the resource server's
10791091
// metadata, and both `code` and `message` are echoed from its response verbatim.
1080-
console.warn(`[mcp-sdk] OAuth ${JSON.stringify(error.code)} — ${action}. Cause: ${JSON.stringify(error.message)}`);
1092+
guardLogger(provider.sdkLogger).warn?.(
1093+
`[mcp-sdk] OAuth ${JSON.stringify(error.code)} — ${action}. Cause: ${JSON.stringify(error.message)}`
1094+
);
10811095
}
10821096

10831097
/**
@@ -1163,6 +1177,7 @@ async function authInternal(
11631177
forceReauthorization
11641178
}: AuthOptions
11651179
): Promise<AuthResult> {
1180+
const logger = guardLogger(provider.sdkLogger);
11661181
// SEP-837 / SEP-2207: resolve spec defaults for the DCR body. determineScope()
11671182
// intentionally reads the raw provider.clientMetadata instead.
11681183
const clientMetadata = resolveClientMetadata(provider);
@@ -1273,7 +1288,7 @@ async function authInternal(
12731288
issuer
12741289
);
12751290
}
1276-
console.warn(
1291+
logger.warn?.(
12771292
'[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); ' +
12781293
'the SEP-2352 callback-leg authorization-server binding cannot be checked. ' +
12791294
'Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.'
@@ -1313,7 +1328,8 @@ async function authInternal(
13131328
// re-registers exactly as if nothing were stored.
13141329
const rawClientInfo = await Promise.resolve(provider.clientInformation(infoCtx));
13151330
let clientInformation = discardIfIssuerMismatch(rawClientInfo, issuer, {
1316-
canPersistStamp: provider.saveClientInformation !== undefined
1331+
canPersistStamp: provider.saveClientInformation !== undefined,
1332+
logger
13171333
});
13181334
if (clientInformation === undefined && rawClientInfo?.issuer && provider.saveClientInformation === undefined) {
13191335
// Static-credential provider (no DCR) whose `expectedIssuer` stamp names a different
@@ -1398,7 +1414,7 @@ async function authInternal(
13981414

13991415
// SEP-2352: a refresh_token stamped for a different authorization server reads back
14001416
// as `undefined`, so it is never POSTed to this AS's token endpoint.
1401-
let tokens = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer);
1417+
let tokens = discardIfIssuerMismatch(await provider.tokens(infoCtx), issuer, { logger });
14021418
if (tokens && tokens.issuer === undefined) {
14031419
// SEP-2352 back-stamp: bind a legacy unstamped token set to the first-resolved AS
14041420
// so the stamp check is effective from the next call onward.
@@ -1439,7 +1455,7 @@ async function authInternal(
14391455
// redirectToAuthorization() is a no-op — so say why it happened.
14401456
// JSON-stringify the cause: on the non-OAuth-shaped path it carries the raw
14411457
// response body, so it is arbitrary attacker-supplied bytes.
1442-
console.warn(
1458+
logger.warn?.(
14431459
`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. ` +
14441460
`Cause: ${JSON.stringify(error instanceof Error ? error.message : String(error))}`
14451461
);

‎packages/client/src/client/authExtensions.ts‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,14 @@
55
* for common machine-to-machine authentication scenarios.
66
*/
77

8-
import type { FetchLike, OAuthClientMetadata, StoredOAuthClientInformation, StoredOAuthTokens } from '@modelcontextprotocol/core-internal';
8+
import type {
9+
FetchLike,
10+
OAuthClientMetadata,
11+
SdkLogger,
12+
StoredOAuthClientInformation,
13+
StoredOAuthTokens
14+
} from '@modelcontextprotocol/core-internal';
15+
import { guardLogger } from '@modelcontextprotocol/core-internal';
916
import type { CryptoKey, JWK } from 'jose';
1017

1118
import type { AddClientAuthentication, OAuthClientProvider } from './auth';
@@ -98,9 +105,9 @@ export function createPrivateKeyJwtAuth(options: {
98105
* The `issuer` stamp for constructor-supplied client information. Omitting `expectedIssuer` is
99106
* deprecated: nothing else says which authorization server such credentials belong to.
100107
*/
101-
function checkedExpectedIssuer(expectedIssuer: string | undefined): string | undefined {
108+
function checkedExpectedIssuer(expectedIssuer: string | undefined, logger: SdkLogger): string | undefined {
102109
if (expectedIssuer === undefined) {
103-
console.warn(
110+
logger.warn?.(
104111
'[mcp-sdk] Omitting `expectedIssuer` is deprecated. Without it, the MCP server decides which authorization ' +
105112
"server receives this client's credentials; pass your authorization server's issuer URL as " +
106113
'`expectedIssuer` so they are only sent there.'
@@ -144,6 +151,12 @@ export interface ClientCredentialsProviderOptions {
144151
* the MCP server advertises.
145152
*/
146153
expectedIssuer?: string;
154+
155+
/**
156+
* Console-compatible sink for SDK warnings about this provider, including those `auth()`
157+
* prints while using it. Defaults to `console`.
158+
*/
159+
logger?: SdkLogger;
147160
}
148161

149162
/**
@@ -166,6 +179,7 @@ export interface ClientCredentialsProviderOptions {
166179
* ```
167180
*/
168181
export class ClientCredentialsProvider implements OAuthClientProvider {
182+
readonly sdkLogger?: SdkLogger;
169183
private _tokens?: StoredOAuthTokens;
170184
private _clientInfo: StoredOAuthClientInformation;
171185
private _clientMetadata: OAuthClientMetadata;
@@ -174,10 +188,11 @@ export class ClientCredentialsProvider implements OAuthClientProvider {
174188
/** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */
175189
constructor(options: ClientCredentialsProviderOptions);
176190
constructor(options: ClientCredentialsProviderOptions) {
191+
this.sdkLogger = options.logger;
177192
this._clientInfo = {
178193
client_id: options.clientId,
179194
client_secret: options.clientSecret,
180-
issuer: checkedExpectedIssuer(options.expectedIssuer)
195+
issuer: checkedExpectedIssuer(options.expectedIssuer, guardLogger(options.logger))
181196
};
182197
this._clientMetadata = {
183198
client_name: options.clientName ?? 'client-credentials-client',
@@ -282,6 +297,12 @@ export interface PrivateKeyJwtProviderOptions {
282297
* Seeds the SEP-2352 issuer stamp — see {@linkcode ClientCredentialsProviderOptions.expectedIssuer}.
283298
*/
284299
expectedIssuer?: string;
300+
301+
/**
302+
* Console-compatible sink for SDK warnings about this provider, including those `auth()`
303+
* prints while using it. Defaults to `console`.
304+
*/
305+
logger?: SdkLogger;
285306
}
286307

287308
/**
@@ -306,6 +327,7 @@ export interface PrivateKeyJwtProviderOptions {
306327
* ```
307328
*/
308329
export class PrivateKeyJwtProvider implements OAuthClientProvider {
330+
readonly sdkLogger?: SdkLogger;
309331
private _tokens?: StoredOAuthTokens;
310332
private _clientInfo: StoredOAuthClientInformation;
311333
private _clientMetadata: OAuthClientMetadata;
@@ -315,9 +337,10 @@ export class PrivateKeyJwtProvider implements OAuthClientProvider {
315337
/** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */
316338
constructor(options: PrivateKeyJwtProviderOptions);
317339
constructor(options: PrivateKeyJwtProviderOptions) {
340+
this.sdkLogger = options.logger;
318341
this._clientInfo = {
319342
client_id: options.clientId,
320-
issuer: checkedExpectedIssuer(options.expectedIssuer)
343+
issuer: checkedExpectedIssuer(options.expectedIssuer, guardLogger(options.logger))
321344
};
322345
this._clientMetadata = {
323346
client_name: options.clientName ?? 'private-key-jwt-client',
@@ -411,6 +434,12 @@ export interface StaticPrivateKeyJwtProviderOptions {
411434
* Seeds the SEP-2352 issuer stamp — see {@linkcode ClientCredentialsProviderOptions.expectedIssuer}.
412435
*/
413436
expectedIssuer?: string;
437+
438+
/**
439+
* Console-compatible sink for SDK warnings about this provider, including those `auth()`
440+
* prints while using it. Defaults to `console`.
441+
*/
442+
logger?: SdkLogger;
414443
}
415444

416445
/**
@@ -421,6 +450,7 @@ export interface StaticPrivateKeyJwtProviderOptions {
421450
* uses it directly for authentication.
422451
*/
423452
export class StaticPrivateKeyJwtProvider implements OAuthClientProvider {
453+
readonly sdkLogger?: SdkLogger;
424454
private _tokens?: StoredOAuthTokens;
425455
private _clientInfo: StoredOAuthClientInformation;
426456
private _clientMetadata: OAuthClientMetadata;
@@ -430,9 +460,10 @@ export class StaticPrivateKeyJwtProvider implements OAuthClientProvider {
430460
/** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */
431461
constructor(options: StaticPrivateKeyJwtProviderOptions);
432462
constructor(options: StaticPrivateKeyJwtProviderOptions) {
463+
this.sdkLogger = options.logger;
433464
this._clientInfo = {
434465
client_id: options.clientId,
435-
issuer: checkedExpectedIssuer(options.expectedIssuer)
466+
issuer: checkedExpectedIssuer(options.expectedIssuer, guardLogger(options.logger))
436467
};
437468
this._clientMetadata = {
438469
client_name: options.clientName ?? 'static-private-key-jwt-client',
@@ -587,6 +618,12 @@ export interface CrossAppAccessProviderOptions {
587618
* Seeds the SEP-2352 issuer stamp — see {@linkcode ClientCredentialsProviderOptions.expectedIssuer}.
588619
*/
589620
expectedIssuer?: string;
621+
622+
/**
623+
* Console-compatible sink for SDK warnings about this provider, including those `auth()`
624+
* prints while using it. Defaults to `console`.
625+
*/
626+
logger?: SdkLogger;
590627
}
591628

592629
/**
@@ -630,6 +667,7 @@ export interface CrossAppAccessProviderOptions {
630667
* ```
631668
*/
632669
export class CrossAppAccessProvider implements OAuthClientProvider {
670+
readonly sdkLogger?: SdkLogger;
633671
private _tokens?: StoredOAuthTokens;
634672
private _clientInfo: StoredOAuthClientInformation;
635673
private _clientMetadata: OAuthClientMetadata;
@@ -643,10 +681,11 @@ export class CrossAppAccessProvider implements OAuthClientProvider {
643681
/** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */
644682
constructor(options: CrossAppAccessProviderOptions);
645683
constructor(options: CrossAppAccessProviderOptions) {
684+
this.sdkLogger = options.logger;
646685
this._clientInfo = {
647686
client_id: options.clientId,
648687
client_secret: options.clientSecret,
649-
issuer: checkedExpectedIssuer(options.expectedIssuer)
688+
issuer: checkedExpectedIssuer(options.expectedIssuer, guardLogger(options.logger))
650689
};
651690
this._clientMetadata = {
652691
client_name: options.clientName ?? 'cross-app-access-client',

0 commit comments

Comments
 (0)