pi-mcp-extension 1.16.2 → 1.16.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/package.json +1 -1
- package/src/auth-challenge.ts +375 -2
- package/src/authorize-flow.ts +140 -5
- package/src/commands.ts +40 -0
- package/src/config-compat.ts +47 -6
- package/src/config.ts +12 -1
- package/src/connect-policy.ts +18 -6
- package/src/connection-coordinator.ts +37 -10
- package/src/errors.ts +6 -1
- package/src/index.ts +16 -1
- package/src/mcp-client.ts +44 -0
- package/src/oauth-provider.ts +50 -6
- package/src/oauth-status.ts +4 -0
- package/src/register-commands.ts +7 -2
- package/src/register-tools.ts +2 -1
- package/src/resource-bridge.ts +133 -6
- package/src/schema-allof.ts +13 -6
- package/src/schema-convert.ts +46 -5
- package/src/server-manager.ts +51 -7
- package/src/tool-content.ts +2 -6
- package/src/tool-result.ts +17 -2
- package/src/transport-factory.ts +42 -5
package/README.md
CHANGED
|
@@ -40,6 +40,8 @@
|
|
|
40
40
|
|
|
41
41
|
> **Prerequisite:** Node.js 22+ and the [Pi coding agent](https://pi.dev).
|
|
42
42
|
|
|
43
|
+
> **Disable MCP for one run:** `pi --no-mcp` also disables this installed extension, even when it replaces `builtin:mcp`. No MCP config is loaded, no servers connect, and no MCP commands or tools are registered. As with Pi, `--no-mcp` has no effect when it appears after `--` or is passed as another option's value.
|
|
44
|
+
|
|
43
45
|
1. **Install the extension** (or run once without installing via `pi -e npm:pi-mcp-extension`):
|
|
44
46
|
```bash
|
|
45
47
|
pi install npm:pi-mcp-extension
|
|
@@ -269,6 +271,11 @@ Configured under `auth` (or `oauth`). Token and client state are persisted per s
|
|
|
269
271
|
| `clientName` (or `oauth.clientName`) | `string` | `pi-mcp/<server name>` | `client_name` sent with Dynamic Client Registration, for servers that only accept known clients |
|
|
270
272
|
| `redirectUrl` (or `oauth.callbackUrl` / `oauth.callbackPort`) | `string` | `http://127.0.0.1:19876/callback` | Local HTTP loopback callback (`localhost`, `127.0.0.1`, or `::1` with path `/callback` and an explicit non-zero port; `callbackPort` maps to `http://127.0.0.1:<port>/callback`). Scans forward from `19876` when omitted; binds the exact host and port when configured. |
|
|
271
273
|
|
|
274
|
+
When both aliases are set, `oauth.callbackPort` (an integer from `1` to `65535`) fills in a missing
|
|
275
|
+
port in `oauth.callbackUrl` (`http://localhost/callback` plus `19877` becomes
|
|
276
|
+
`http://localhost:19877/callback`); an invalid `callbackPort` or a different port in the URL is a
|
|
277
|
+
config error. Port 80 is HTTP's default and counts as missing.
|
|
278
|
+
|
|
272
279
|
## Commands
|
|
273
280
|
|
|
274
281
|
Server-name arguments provide autocomplete suggestions from the configured MCP servers. `/mcp:auth` suggests only servers configured for OAuth.
|
|
@@ -292,7 +299,7 @@ In addition to user slash commands, built-in **agent tools** let the LLM inspect
|
|
|
292
299
|
| `mcp_status` | `{}` | List configured servers with `lifecycle`, `state`, `tools` (`discovered` / `active` / `expected`, plus optional `inactiveDirect` / `indirectFiltered`), `auth` credential summary, `source` (`"global"` / `"project"` / `"extension"` / `"unknown"`), optional `instructions` (when connected), and safe `error` action hints (never returns tokens, headers, or authorization URLs) |
|
|
293
300
|
| `mcp_connect` | `{ name: string }` | Connect one named server, run interactive OAuth if needed, and verify that the tools configured `direct` are active before returning success (includes sanitized server `instructions` when provided; returns fixed actionable categories on failure instead of raw server response text) |
|
|
294
301
|
| `mcp_list_resources` | `{ server?: string }` | List `resources/list` entries (`uri`, `name`, `description`, `mimeType`) and `resources/templates/list` URI templates for connected servers, naming configured servers that are stopped (`stoppedServers`), servers that do not advertise the `resources` capability (`resourcesUnsupported`), and servers whose listing failed (`error`) without dropping the healthy servers' rows (read-only) |
|
|
295
|
-
| `mcp_read_resource` | `{ server: string, uri: string }` | Read one resource with `resources/read`: text resources return their text (including empty text), `image/*` blobs return an image block, and other binary blobs return a `[Binary resource: uri (mimeType,
|
|
302
|
+
| `mcp_read_resource` | `{ server: string, uri: string }` | Read one resource with `resources/read`: text resources return their text (including empty text), valid `image/svg+xml` blobs decode to UTF-8 SVG text, supported `image/*` raster blobs (`png`, `jpeg`, `gif`, `webp`, `bmp`, `tiff`) return an image block, and other binary blobs (including empty/invalid or unsupported `image/*` blobs) return a `[Binary resource: uri (mimeType, ...)]` summary instead of filling the context window or breaking provider adapters; a server without the `resources` capability is reported as such rather than as a protocol error (read-only) |
|
|
296
303
|
|
|
297
304
|
`mcp_status` returns a JSON array of [`ServerStatusRow`](./src/server-status.ts) objects:
|
|
298
305
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-extension",
|
|
3
|
-
"version": "1.16.
|
|
3
|
+
"version": "1.16.4",
|
|
4
4
|
"description": "Full-featured, lightweight MCP extension for the Pi coding agent: stdio, SSE & Streamable HTTP transports, OAuth 2.1 (PKCE + DCR), lazy/eager lifecycles — minimal dependencies, zero bloat.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
package/src/auth-challenge.ts
CHANGED
|
@@ -1,14 +1,387 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* OAuth challenge discovery
|
|
2
|
+
* OAuth challenge discovery, 403 insufficient_scope capture, and step-up scope helpers.
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import { extractWWWAuthenticateParams } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
5
|
+
import { extractWWWAuthenticateParams, UnauthorizedError } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
6
|
+
import { canonicalServerUrl, urlsMatch } from "./oauth-policy.js";
|
|
6
7
|
|
|
7
8
|
export interface ManualAuthChallenge {
|
|
8
9
|
resourceMetadataUrl?: URL | undefined;
|
|
9
10
|
scope?: string | undefined;
|
|
10
11
|
}
|
|
11
12
|
|
|
13
|
+
export interface PendingAuthChallenge {
|
|
14
|
+
serverUrl: string;
|
|
15
|
+
resourceMetadataUrl?: URL | undefined;
|
|
16
|
+
scope?: string | undefined;
|
|
17
|
+
grantedScope?: string | undefined;
|
|
18
|
+
error?: string | undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface CapturedAuthChallenge {
|
|
22
|
+
status: 401 | 403;
|
|
23
|
+
serverUrl: string;
|
|
24
|
+
resourceMetadataUrl?: URL | undefined;
|
|
25
|
+
scope?: string | undefined;
|
|
26
|
+
grantedScope?: string | undefined;
|
|
27
|
+
error?: string | undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ChallengeCaptureFetchOptions {
|
|
31
|
+
baseFetch?: typeof fetch | undefined;
|
|
32
|
+
rejectInsufficientScope?: boolean | undefined;
|
|
33
|
+
/**
|
|
34
|
+
* When true, only capture `403 insufficient_scope` from HTTP `POST` requests.
|
|
35
|
+
*
|
|
36
|
+
* WHY: On Streamable HTTP, `StreamableHTTPClientTransport._startOrAuthSse` fires
|
|
37
|
+
* an unawaited optional `GET` probe (and `terminateSession` fires `DELETE`), neither
|
|
38
|
+
* of which upscopes on `403`. Gating `403` capture to `POST` prevents an ignored
|
|
39
|
+
* optional `GET` (or teardown `DELETE`) response from silently poisoning
|
|
40
|
+
* `pendingAuthChallenge` on a `ready` server.
|
|
41
|
+
*/
|
|
42
|
+
capture403PostOnly?: boolean | undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function splitScopeTokens(raw: string | undefined): string[] {
|
|
46
|
+
if (!raw) return [];
|
|
47
|
+
return raw.trim().split(/\s+/).filter(Boolean);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function dedupeScopeTokens(tokens: readonly string[]): string | undefined {
|
|
51
|
+
const unique: string[] = [];
|
|
52
|
+
const seen = new Set<string>();
|
|
53
|
+
for (const token of tokens) {
|
|
54
|
+
if (!seen.has(token)) {
|
|
55
|
+
seen.add(token);
|
|
56
|
+
unique.push(token);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return unique.length > 0 ? unique.join(" ") : undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Compute a deduplicated space-delimited step-up scope union across
|
|
64
|
+
* `configuredScope`, `grantedScope`, and `challengedScope`.
|
|
65
|
+
*
|
|
66
|
+
* When `challengedScope` is absent or blank, returns `undefined` so the SDK follows
|
|
67
|
+
* SEP-835 (`resourceMetadata.scopes_supported`, then `provider.clientMetadata.scope` /
|
|
68
|
+
* `config.auth.scope`) instead of repeating an insufficient grant.
|
|
69
|
+
*/
|
|
70
|
+
export function mergeStepUpScope(
|
|
71
|
+
configuredScope: string | undefined,
|
|
72
|
+
grantedScope: string | undefined,
|
|
73
|
+
challengedScope: string | undefined,
|
|
74
|
+
): string | undefined {
|
|
75
|
+
const challenged = splitScopeTokens(challengedScope);
|
|
76
|
+
if (challenged.length === 0) {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
return dedupeScopeTokens([
|
|
80
|
+
...splitScopeTokens(configuredScope),
|
|
81
|
+
...splitScopeTokens(grantedScope),
|
|
82
|
+
...challenged,
|
|
83
|
+
]);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function normalizeScopeTokens(raw: string | undefined): string | undefined {
|
|
87
|
+
return dedupeScopeTokens(splitScopeTokens(raw));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function mergeInsufficientScopeChallenge(
|
|
91
|
+
prior: PendingAuthChallenge | undefined,
|
|
92
|
+
incoming: CapturedAuthChallenge,
|
|
93
|
+
): PendingAuthChallenge {
|
|
94
|
+
const isPriorStepUp = prior?.error === "insufficient_scope";
|
|
95
|
+
const priorChallenged = isPriorStepUp ? prior.scope : undefined;
|
|
96
|
+
const scope = dedupeScopeTokens([
|
|
97
|
+
...splitScopeTokens(priorChallenged),
|
|
98
|
+
...splitScopeTokens(incoming.scope),
|
|
99
|
+
]);
|
|
100
|
+
const resourceMetadataUrl = incoming.resourceMetadataUrl ?? prior?.resourceMetadataUrl;
|
|
101
|
+
// WHY: Keep the earliest captured grantedScope across retries (e.g. a refresh retry that
|
|
102
|
+
// omits or narrows scope must not clobber the token scope that originally hit 403).
|
|
103
|
+
const priorGranted = isPriorStepUp ? normalizeScopeTokens(prior.grantedScope) : undefined;
|
|
104
|
+
const grantedScope = priorGranted ?? normalizeScopeTokens(incoming.grantedScope);
|
|
105
|
+
return {
|
|
106
|
+
serverUrl: incoming.serverUrl,
|
|
107
|
+
error: "insufficient_scope",
|
|
108
|
+
...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),
|
|
109
|
+
...(scope ? { scope } : {}),
|
|
110
|
+
...(grantedScope ? { grantedScope } : {}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Merge an incoming 401/403 challenge into any pending server challenge.
|
|
116
|
+
*
|
|
117
|
+
* A subsequent 401 (such as the silent `startServer()` probe before `/mcp:auth`)
|
|
118
|
+
* never overwrites an existing `insufficient_scope` challenge's `error`, `scope`,
|
|
119
|
+
* or `grantedScope`, and repeated `403` challenges union scopes while keeping the
|
|
120
|
+
* earliest captured `grantedScope`.
|
|
121
|
+
*/
|
|
122
|
+
export function mergePendingAuthChallenge(
|
|
123
|
+
existing: PendingAuthChallenge | undefined,
|
|
124
|
+
incoming: CapturedAuthChallenge,
|
|
125
|
+
): PendingAuthChallenge {
|
|
126
|
+
const prior = existing && urlsMatch(existing.serverUrl, incoming.serverUrl) ? existing : undefined;
|
|
127
|
+
if (incoming.error === "insufficient_scope") {
|
|
128
|
+
return mergeInsufficientScopeChallenge(prior, incoming);
|
|
129
|
+
}
|
|
130
|
+
if (prior?.error === "insufficient_scope") {
|
|
131
|
+
const resourceMetadataUrl = prior.resourceMetadataUrl ?? incoming.resourceMetadataUrl;
|
|
132
|
+
return {
|
|
133
|
+
...prior,
|
|
134
|
+
...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
const grantedScope = normalizeScopeTokens(incoming.grantedScope);
|
|
138
|
+
return {
|
|
139
|
+
serverUrl: incoming.serverUrl,
|
|
140
|
+
...(incoming.resourceMetadataUrl ? { resourceMetadataUrl: incoming.resourceMetadataUrl } : {}),
|
|
141
|
+
...(incoming.scope ? { scope: incoming.scope } : {}),
|
|
142
|
+
...(grantedScope ? { grantedScope } : {}),
|
|
143
|
+
...(incoming.error ? { error: incoming.error } : {}),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Attach a token's granted scope to a pending `insufficient_scope` challenge
|
|
149
|
+
* if it does not already carry one.
|
|
150
|
+
*/
|
|
151
|
+
export function withGrantedScope(
|
|
152
|
+
pending: PendingAuthChallenge | undefined,
|
|
153
|
+
grantedScope: string | undefined,
|
|
154
|
+
): PendingAuthChallenge | undefined {
|
|
155
|
+
if (!pending || pending.error !== "insufficient_scope" || normalizeScopeTokens(pending.grantedScope)) {
|
|
156
|
+
return pending;
|
|
157
|
+
}
|
|
158
|
+
const normalized = normalizeScopeTokens(grantedScope);
|
|
159
|
+
return normalized ? { ...pending, grantedScope: normalized } : pending;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Return true when `pending` is a `403 insufficient_scope` step-up challenge
|
|
164
|
+
* bound to `serverUrl`.
|
|
165
|
+
*/
|
|
166
|
+
export function isPendingStepUpChallenge(
|
|
167
|
+
pending: PendingAuthChallenge | undefined,
|
|
168
|
+
serverUrl: string | undefined,
|
|
169
|
+
): boolean {
|
|
170
|
+
return (
|
|
171
|
+
pending?.error === "insufficient_scope" &&
|
|
172
|
+
typeof serverUrl === "string" &&
|
|
173
|
+
urlsMatch(pending.serverUrl, serverUrl)
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Whether `ConnectionCoordinator._tryStartServer` should skip a silent connect
|
|
179
|
+
* attempt and proceed directly to interactive authorization.
|
|
180
|
+
*/
|
|
181
|
+
export function shouldSkipInteractivePreStart(params: {
|
|
182
|
+
reset: boolean;
|
|
183
|
+
hasUI: boolean;
|
|
184
|
+
hasAuth: boolean;
|
|
185
|
+
serverUrl: string | undefined;
|
|
186
|
+
pending: PendingAuthChallenge | undefined;
|
|
187
|
+
}): boolean {
|
|
188
|
+
if (params.reset) return true;
|
|
189
|
+
if (!params.hasUI || !params.hasAuth) return false;
|
|
190
|
+
return isPendingStepUpChallenge(params.pending, params.serverUrl);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Record an incoming OAuth challenge onto `target` only while `isCurrent()` holds,
|
|
195
|
+
* preventing late-settling responses from a shut-down or replaced transport from
|
|
196
|
+
* polluting `pendingAuthChallenge`.
|
|
197
|
+
*/
|
|
198
|
+
export function applyPendingAuthChallenge(
|
|
199
|
+
target: { pendingAuthChallenge?: PendingAuthChallenge | undefined },
|
|
200
|
+
incoming: CapturedAuthChallenge,
|
|
201
|
+
isCurrent: () => boolean,
|
|
202
|
+
): void {
|
|
203
|
+
if (!isCurrent()) return;
|
|
204
|
+
target.pendingAuthChallenge = mergePendingAuthChallenge(target.pendingAuthChallenge, incoming);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Attach a token's granted scope onto `target.pendingAuthChallenge` when present.
|
|
209
|
+
*/
|
|
210
|
+
export function attachPendingGrantedScope(
|
|
211
|
+
target: { pendingAuthChallenge?: PendingAuthChallenge | undefined } | undefined,
|
|
212
|
+
scope: string | undefined,
|
|
213
|
+
): void {
|
|
214
|
+
if (!target) return;
|
|
215
|
+
target.pendingAuthChallenge = withGrantedScope(target.pendingAuthChallenge, scope);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Resolve the effective OAuth challenge for `authorize()`, preserving any pending
|
|
220
|
+
* `403 insufficient_scope` challenge ahead of a baseline `401` probe.
|
|
221
|
+
*/
|
|
222
|
+
export function resolveAuthorizeChallenge(params: {
|
|
223
|
+
configuredScope?: string | undefined;
|
|
224
|
+
pending?: PendingAuthChallenge | undefined;
|
|
225
|
+
discovered: ManualAuthChallenge;
|
|
226
|
+
storedTokenScope?: string | undefined;
|
|
227
|
+
}): ManualAuthChallenge {
|
|
228
|
+
const { configuredScope, pending, discovered, storedTokenScope } = params;
|
|
229
|
+
if (pending?.error !== "insufficient_scope") {
|
|
230
|
+
return {
|
|
231
|
+
...(discovered.resourceMetadataUrl ? { resourceMetadataUrl: discovered.resourceMetadataUrl } : {}),
|
|
232
|
+
...(discovered.scope ? { scope: discovered.scope } : {}),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
const resourceMetadataUrl = pending.resourceMetadataUrl ?? discovered.resourceMetadataUrl;
|
|
236
|
+
const effectiveGranted =
|
|
237
|
+
normalizeScopeTokens(pending.grantedScope) ??
|
|
238
|
+
normalizeScopeTokens(storedTokenScope) ??
|
|
239
|
+
discovered.scope;
|
|
240
|
+
const scope = mergeStepUpScope(configuredScope, effectiveGranted, pending.scope);
|
|
241
|
+
return {
|
|
242
|
+
...(resourceMetadataUrl ? { resourceMetadataUrl } : {}),
|
|
243
|
+
...(scope ? { scope } : {}),
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Whether interactive step-up authorization must invalidate cached `discoveryState`
|
|
249
|
+
* before calling the MCP SDK's `auth()`.
|
|
250
|
+
*
|
|
251
|
+
* WHY: The SDK's `authInternal()` short-circuits Protected Resource Metadata (PRM)
|
|
252
|
+
* discovery whenever `discoveryState.authorizationServerUrl` and `resourceMetadata`
|
|
253
|
+
* are cached on disk, silently ignoring a new `resourceMetadataUrl` option or updated
|
|
254
|
+
* `scopes_supported`. Invalidating only `"discovery"` (keeping `clientInfo` and its
|
|
255
|
+
* issuer binding intact) ensures a `403 insufficient_scope` challenge with a different
|
|
256
|
+
* `resource_metadata` URL or an omitted `scope` fetches fresh PRM metadata.
|
|
257
|
+
*/
|
|
258
|
+
export function shouldInvalidateDiscoveryForStepUp(params: {
|
|
259
|
+
pending: PendingAuthChallenge | undefined;
|
|
260
|
+
challengeResourceMetadataUrl: URL | undefined;
|
|
261
|
+
cachedResourceMetadataUrl: string | undefined;
|
|
262
|
+
}): boolean {
|
|
263
|
+
const { pending, challengeResourceMetadataUrl, cachedResourceMetadataUrl } = params;
|
|
264
|
+
if (pending?.error !== "insufficient_scope") return false;
|
|
265
|
+
if (!normalizeScopeTokens(pending.scope)) return true;
|
|
266
|
+
if (!challengeResourceMetadataUrl) return false;
|
|
267
|
+
return (
|
|
268
|
+
!cachedResourceMetadataUrl ||
|
|
269
|
+
!urlsMatch(cachedResourceMetadataUrl, challengeResourceMetadataUrl.href)
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function extractRequestUrl(input: Parameters<typeof fetch>[0]): string {
|
|
274
|
+
if (typeof input === "string") return input;
|
|
275
|
+
if (input instanceof URL) return input.href;
|
|
276
|
+
return input.url;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function extractRequestMethod(
|
|
280
|
+
input: Parameters<typeof fetch>[0],
|
|
281
|
+
init?: RequestInit,
|
|
282
|
+
): string {
|
|
283
|
+
if (init?.method) return init.method.toUpperCase();
|
|
284
|
+
if (typeof Request !== "undefined" && input instanceof Request) {
|
|
285
|
+
return input.method.toUpperCase();
|
|
286
|
+
}
|
|
287
|
+
return "GET";
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function parseServerOrigin(canonicalUrl: string): string | undefined {
|
|
291
|
+
try {
|
|
292
|
+
return new URL(canonicalUrl).origin;
|
|
293
|
+
} catch {
|
|
294
|
+
// WHY: Malformed serverUrl cannot match any HTTP request origin.
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function isSameOriginRequest(input: Parameters<typeof fetch>[0], expectedOrigin: string): boolean {
|
|
300
|
+
try {
|
|
301
|
+
return new URL(extractRequestUrl(input)).origin === expectedOrigin;
|
|
302
|
+
} catch {
|
|
303
|
+
// WHY: Malformed or relative request URLs cannot verify origin binding.
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function buildCapturedChallenge(
|
|
309
|
+
status: 401 | 403,
|
|
310
|
+
serverUrl: string,
|
|
311
|
+
params: { resourceMetadataUrl?: URL | undefined; scope?: string | undefined; error?: string | undefined },
|
|
312
|
+
): CapturedAuthChallenge {
|
|
313
|
+
const challenge: CapturedAuthChallenge = { status, serverUrl };
|
|
314
|
+
if (params.resourceMetadataUrl) challenge.resourceMetadataUrl = params.resourceMetadataUrl;
|
|
315
|
+
if (params.scope) challenge.scope = params.scope;
|
|
316
|
+
if (params.error) challenge.error = params.error;
|
|
317
|
+
return challenge;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
interface CapturedResponseContext {
|
|
321
|
+
response: Response;
|
|
322
|
+
canonicalUrl: string;
|
|
323
|
+
onChallenge: (challenge: CapturedAuthChallenge) => void;
|
|
324
|
+
rejectInsufficientScope: boolean;
|
|
325
|
+
allow403Capture: boolean;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
async function handleCapturedResponse(ctx: CapturedResponseContext): Promise<Response> {
|
|
329
|
+
const { response, canonicalUrl, onChallenge, rejectInsufficientScope, allow403Capture } = ctx;
|
|
330
|
+
if (response.status !== 401 && response.status !== 403) {
|
|
331
|
+
return response;
|
|
332
|
+
}
|
|
333
|
+
const params = extractWWWAuthenticateParams(response);
|
|
334
|
+
if (response.status === 401) {
|
|
335
|
+
if (params.resourceMetadataUrl !== undefined || params.scope !== undefined) {
|
|
336
|
+
onChallenge(buildCapturedChallenge(401, canonicalUrl, params));
|
|
337
|
+
}
|
|
338
|
+
return response;
|
|
339
|
+
}
|
|
340
|
+
if (!allow403Capture || params.error !== "insufficient_scope") {
|
|
341
|
+
return response;
|
|
342
|
+
}
|
|
343
|
+
onChallenge(buildCapturedChallenge(403, canonicalUrl, params));
|
|
344
|
+
if (rejectInsufficientScope) {
|
|
345
|
+
await response.body?.cancel().catch(() => {
|
|
346
|
+
// WHY: Release the HTTP response body before rejecting SSE transport on 403 insufficient_scope.
|
|
347
|
+
});
|
|
348
|
+
throw new UnauthorizedError("HTTP 403 insufficient_scope");
|
|
349
|
+
}
|
|
350
|
+
return response;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Wrap `fetch` to capture same-origin `401` and `403 insufficient_scope`
|
|
355
|
+
* `WWW-Authenticate` challenges from an MCP resource server.
|
|
356
|
+
*/
|
|
357
|
+
export function createChallengeCaptureFetch(
|
|
358
|
+
serverUrl: string,
|
|
359
|
+
onChallenge: (challenge: CapturedAuthChallenge) => void,
|
|
360
|
+
options?: ChallengeCaptureFetchOptions,
|
|
361
|
+
): typeof fetch {
|
|
362
|
+
const baseFetch = options?.baseFetch ?? fetch;
|
|
363
|
+
const canonicalUrl = canonicalServerUrl(serverUrl);
|
|
364
|
+
const expectedOrigin = parseServerOrigin(canonicalUrl);
|
|
365
|
+
if (!expectedOrigin) return baseFetch;
|
|
366
|
+
const rejectInsufficientScope = options?.rejectInsufficientScope === true;
|
|
367
|
+
const capture403PostOnly = options?.capture403PostOnly === true;
|
|
368
|
+
|
|
369
|
+
return async (input, init) => {
|
|
370
|
+
const response = await baseFetch(input, init);
|
|
371
|
+
if (!isSameOriginRequest(input, expectedOrigin)) {
|
|
372
|
+
return response;
|
|
373
|
+
}
|
|
374
|
+
const allow403Capture = !capture403PostOnly || extractRequestMethod(input, init) === "POST";
|
|
375
|
+
return handleCapturedResponse({
|
|
376
|
+
response,
|
|
377
|
+
canonicalUrl,
|
|
378
|
+
onChallenge,
|
|
379
|
+
rejectInsufficientScope,
|
|
380
|
+
allow403Capture,
|
|
381
|
+
});
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
12
385
|
export type AuthChallengeFetch = (input: string | URL, init?: RequestInit) => Promise<Response>;
|
|
13
386
|
|
|
14
387
|
export const AUTH_CHALLENGE_TIMEOUT_MS = 10_000;
|
package/src/authorize-flow.ts
CHANGED
|
@@ -5,9 +5,13 @@ import { callbackServerConfigFromRedirectUrl } from "./callback-url.js";
|
|
|
5
5
|
import {
|
|
6
6
|
discoverManualAuthChallenge,
|
|
7
7
|
createHeadersFetch,
|
|
8
|
+
resolveAuthorizeChallenge,
|
|
9
|
+
shouldInvalidateDiscoveryForStepUp,
|
|
8
10
|
stripAuthorizationHeader,
|
|
9
11
|
type ManualAuthChallenge,
|
|
12
|
+
type PendingAuthChallenge,
|
|
10
13
|
} from "./auth-challenge.js";
|
|
14
|
+
import { urlsMatch } from "./oauth-policy.js";
|
|
11
15
|
import { acquireAuthLock, type AuthLockHandle } from "./auth-lock.js";
|
|
12
16
|
import { McpOAuthProvider } from "./oauth-provider.js";
|
|
13
17
|
import { McpError, AuthCancelledError, AuthLockError } from "./errors.js";
|
|
@@ -166,6 +170,117 @@ function reportCorruptOAuthState(serverName: string, err: McpError): void {
|
|
|
166
170
|
});
|
|
167
171
|
}
|
|
168
172
|
|
|
173
|
+
function readPendingChallenge(
|
|
174
|
+
deps: AuthorizeDeps,
|
|
175
|
+
serverName: string,
|
|
176
|
+
serverUrl: string,
|
|
177
|
+
reset: boolean,
|
|
178
|
+
): PendingAuthChallenge | undefined {
|
|
179
|
+
if (reset) return undefined;
|
|
180
|
+
const pending = deps.manager.getPendingAuthChallenge?.(serverName);
|
|
181
|
+
if (!pending || !urlsMatch(pending.serverUrl, serverUrl)) return undefined;
|
|
182
|
+
return pending;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async function readStoredTokenScopeForStepUp(
|
|
186
|
+
authProvider: McpOAuthProvider,
|
|
187
|
+
pending: PendingAuthChallenge | undefined,
|
|
188
|
+
serverName: string,
|
|
189
|
+
): Promise<string | undefined> {
|
|
190
|
+
if (pending?.error !== "insufficient_scope" || pending.grantedScope?.trim()) {
|
|
191
|
+
return undefined;
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
return (await authProvider.tokens())?.scope;
|
|
195
|
+
} catch (err) {
|
|
196
|
+
if (!isCorruptOAuthStateError(err)) throw err;
|
|
197
|
+
reportCorruptOAuthState(serverName, err);
|
|
198
|
+
return undefined;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function prepareStepUpAuthState(params: {
|
|
203
|
+
deps: AuthorizeDeps;
|
|
204
|
+
authProvider: McpOAuthProvider;
|
|
205
|
+
serverName: string;
|
|
206
|
+
serverUrl: string;
|
|
207
|
+
reset: boolean;
|
|
208
|
+
assertActive: () => void;
|
|
209
|
+
}): Promise<{ pendingChallenge: PendingAuthChallenge | undefined; storedTokenScope: string | undefined }> {
|
|
210
|
+
const { deps, authProvider, serverName, serverUrl, reset, assertActive } = params;
|
|
211
|
+
const pendingChallenge = readPendingChallenge(deps, serverName, serverUrl, reset);
|
|
212
|
+
const storedTokenScope = await readStoredTokenScopeForStepUp(
|
|
213
|
+
authProvider,
|
|
214
|
+
pendingChallenge,
|
|
215
|
+
serverName,
|
|
216
|
+
);
|
|
217
|
+
assertActive();
|
|
218
|
+
if (storedTokenScope) {
|
|
219
|
+
// WHY: Persist storedTokenScope onto the pending challenge before clearing disk tokens
|
|
220
|
+
// so cancelling interactive auth and retrying still retains previously granted scopes.
|
|
221
|
+
deps.manager.recordPendingAuthGrantedScope?.(serverName, storedTokenScope);
|
|
222
|
+
}
|
|
223
|
+
if (!reset) {
|
|
224
|
+
await clearStoredTokensBeforeInteractiveAuth(authProvider, serverName);
|
|
225
|
+
assertActive();
|
|
226
|
+
}
|
|
227
|
+
return { pendingChallenge, storedTokenScope };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function readCachedResourceMetadataUrl(
|
|
231
|
+
authProvider: McpOAuthProvider,
|
|
232
|
+
serverName: string,
|
|
233
|
+
): Promise<{ exists: boolean; resourceMetadataUrl: string | undefined }> {
|
|
234
|
+
try {
|
|
235
|
+
const cached = await authProvider.discoveryState();
|
|
236
|
+
return {
|
|
237
|
+
exists: cached !== undefined,
|
|
238
|
+
resourceMetadataUrl: cached?.resourceMetadataUrl,
|
|
239
|
+
};
|
|
240
|
+
} catch (err) {
|
|
241
|
+
if (!isCorruptOAuthStateError(err)) throw err;
|
|
242
|
+
reportCorruptOAuthState(serverName, err);
|
|
243
|
+
return { exists: false, resourceMetadataUrl: undefined };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function invalidateDiscoveryForStepUpIfNeeded(params: {
|
|
248
|
+
authProvider: McpOAuthProvider;
|
|
249
|
+
pending: PendingAuthChallenge | undefined;
|
|
250
|
+
authChallenge: ManualAuthChallenge;
|
|
251
|
+
serverName: string;
|
|
252
|
+
assertActive: () => void;
|
|
253
|
+
}): Promise<void> {
|
|
254
|
+
const { authProvider, pending, authChallenge, serverName, assertActive } = params;
|
|
255
|
+
if (pending?.error !== "insufficient_scope") return;
|
|
256
|
+
const cached = await readCachedResourceMetadataUrl(authProvider, serverName);
|
|
257
|
+
assertActive();
|
|
258
|
+
if (!cached.exists) return;
|
|
259
|
+
const shouldInvalidate = shouldInvalidateDiscoveryForStepUp({
|
|
260
|
+
pending,
|
|
261
|
+
challengeResourceMetadataUrl: authChallenge.resourceMetadataUrl,
|
|
262
|
+
cachedResourceMetadataUrl: cached.resourceMetadataUrl,
|
|
263
|
+
});
|
|
264
|
+
if (!shouldInvalidate) return;
|
|
265
|
+
try {
|
|
266
|
+
await authProvider.invalidateCredentials("discovery");
|
|
267
|
+
} catch (err) {
|
|
268
|
+
if (!isCorruptOAuthStateError(err)) throw err;
|
|
269
|
+
reportCorruptOAuthState(serverName, err);
|
|
270
|
+
}
|
|
271
|
+
assertActive();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function applyRedirectFallbackScope(
|
|
275
|
+
authProvider: McpOAuthProvider,
|
|
276
|
+
latestAuthorizationUrl: URL | undefined,
|
|
277
|
+
): void {
|
|
278
|
+
const requestedScope = latestAuthorizationUrl?.searchParams.get("scope");
|
|
279
|
+
if (requestedScope) {
|
|
280
|
+
authProvider.setFallbackTokenScope(requestedScope);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
169
284
|
function notifyAuthorizationSucceeded(ctx: ExtensionContext, serverName: string): void {
|
|
170
285
|
ctx.ui.notify(`pi-mcp: ${serverName} authenticated successfully. Starting MCP server...`, "info");
|
|
171
286
|
}
|
|
@@ -516,10 +631,14 @@ export async function authorize(
|
|
|
516
631
|
onAuthRequired: launchAuthorizationBrowser,
|
|
517
632
|
});
|
|
518
633
|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
634
|
+
const { pendingChallenge, storedTokenScope } = await prepareStepUpAuthState({
|
|
635
|
+
deps,
|
|
636
|
+
authProvider,
|
|
637
|
+
serverName,
|
|
638
|
+
serverUrl,
|
|
639
|
+
reset,
|
|
640
|
+
assertActive,
|
|
641
|
+
});
|
|
523
642
|
|
|
524
643
|
// Why set state before calling auth(): the SDK reads provider.state() while
|
|
525
644
|
// building the authorization URL inside auth(), and omits the state parameter
|
|
@@ -532,13 +651,27 @@ export async function authorize(
|
|
|
532
651
|
// authorization server is usually a different origin.
|
|
533
652
|
const staticHeaders = stripAuthorizationHeader(config.headers);
|
|
534
653
|
|
|
535
|
-
const
|
|
654
|
+
const discoveredChallenge = await discoverChallengeWithFallback({
|
|
536
655
|
serverName,
|
|
537
656
|
serverUrl,
|
|
538
657
|
headers: staticHeaders,
|
|
539
658
|
signal,
|
|
540
659
|
});
|
|
541
660
|
assertActive();
|
|
661
|
+
const authChallenge = resolveAuthorizeChallenge({
|
|
662
|
+
configuredScope: config.auth?.scope,
|
|
663
|
+
pending: pendingChallenge,
|
|
664
|
+
discovered: discoveredChallenge,
|
|
665
|
+
storedTokenScope,
|
|
666
|
+
});
|
|
667
|
+
await invalidateDiscoveryForStepUpIfNeeded({
|
|
668
|
+
authProvider,
|
|
669
|
+
pending: pendingChallenge,
|
|
670
|
+
authChallenge,
|
|
671
|
+
serverName,
|
|
672
|
+
assertActive,
|
|
673
|
+
});
|
|
674
|
+
authProvider.setFallbackTokenScope(authChallenge.scope ?? config.auth?.scope);
|
|
542
675
|
|
|
543
676
|
const callbackPromise = registerCallbackPromise(callbackServer, oauthState);
|
|
544
677
|
const customFetch = staticHeaders ? createHeadersFetch(staticHeaders) : undefined;
|
|
@@ -554,6 +687,7 @@ export async function authorize(
|
|
|
554
687
|
// Auth succeeded without needing browser interaction (e.g., had valid tokens).
|
|
555
688
|
notifyAuthorizationSucceeded(ctx, serverName);
|
|
556
689
|
} else if (authResult === "REDIRECT") {
|
|
690
|
+
applyRedirectFallbackScope(authProvider, state.latestAuthorizationUrl);
|
|
557
691
|
await completeRedirectAuthFlow({
|
|
558
692
|
serverName,
|
|
559
693
|
serverUrl,
|
|
@@ -581,6 +715,7 @@ export async function authorize(
|
|
|
581
715
|
}
|
|
582
716
|
|
|
583
717
|
assertActive();
|
|
718
|
+
deps.manager.clearPendingAuthChallenge?.(serverName);
|
|
584
719
|
reportDiagnostic({
|
|
585
720
|
level: "info",
|
|
586
721
|
event: "auth.completed",
|
package/src/commands.ts
CHANGED
|
@@ -135,4 +135,44 @@ export function authArgumentCompletions(argumentPrefix: string, servers: readonl
|
|
|
135
135
|
return completions.length > 0 ? completions : null;
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
+
// WHY: Pi 1.3.0 only reports --no-mcp through its own parsed arguments; extensions cannot
|
|
139
|
+
// read that setting from ExtensionAPI. Mirror its value-taking flags to avoid treating
|
|
140
|
+
// an option's value as the --no-mcp switch.
|
|
141
|
+
const PI_VALUE_TAKING_FLAGS: ReadonlySet<string> = new Set([
|
|
142
|
+
"--provider",
|
|
143
|
+
"--model",
|
|
144
|
+
"--api-key",
|
|
145
|
+
"--system-prompt",
|
|
146
|
+
"--append-system-prompt",
|
|
147
|
+
"--name",
|
|
148
|
+
"-n",
|
|
149
|
+
"--session",
|
|
150
|
+
"--session-id",
|
|
151
|
+
"--fork",
|
|
152
|
+
"--session-dir",
|
|
153
|
+
"--models",
|
|
154
|
+
"--tools",
|
|
155
|
+
"-t",
|
|
156
|
+
"--exclude-tools",
|
|
157
|
+
"-xt",
|
|
158
|
+
"--thinking",
|
|
159
|
+
"--export",
|
|
160
|
+
"--extension",
|
|
161
|
+
"-e",
|
|
162
|
+
"--skill",
|
|
163
|
+
"--prompt-template",
|
|
164
|
+
"--theme",
|
|
165
|
+
]);
|
|
166
|
+
|
|
167
|
+
/** Return true only when Pi receives --no-mcp as a CLI flag, not as a value or positional argument. */
|
|
168
|
+
export function hasNoMcpFlag(argv: readonly string[]): boolean {
|
|
169
|
+
for (let i = 0; i < argv.length; i++) {
|
|
170
|
+
const arg = argv[i] ?? "";
|
|
171
|
+
if (arg === "--") break;
|
|
172
|
+
if (arg === "--no-mcp") return true;
|
|
173
|
+
if (PI_VALUE_TAKING_FLAGS.has(arg)) i++;
|
|
174
|
+
}
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
|
|
138
178
|
export { collectRegisteredServers, mergeWithRegisteredServers } from "./session-lifecycle.js";
|