pi-mcp-adapter 2.37.0 → 3.0.0

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +53 -1
  2. package/OAUTH.md +369 -0
  3. package/README.md +67 -52
  4. package/cli.js +9 -9
  5. package/commands.ts +21 -10
  6. package/config.ts +230 -43
  7. package/direct-tool-surface.ts +2 -2
  8. package/direct-tools.ts +7 -5
  9. package/dist/config.d.ts +13 -0
  10. package/dist/config.js +217 -41
  11. package/dist/config.js.map +1 -1
  12. package/dist/json-schema-validator.js +15 -2
  13. package/dist/json-schema-validator.js.map +1 -1
  14. package/dist/mcp-auth.d.ts +2 -0
  15. package/dist/mcp-auth.js +27 -2
  16. package/dist/mcp-auth.js.map +1 -1
  17. package/dist/metadata-cache.js +1 -1
  18. package/dist/metadata-cache.js.map +1 -1
  19. package/dist/package-mcp-loader.d.ts +9 -1
  20. package/dist/package-mcp-loader.js +8 -4
  21. package/dist/package-mcp-loader.js.map +1 -1
  22. package/dist/server-manager.js +6 -4
  23. package/dist/server-manager.js.map +1 -1
  24. package/dist/state.d.ts +5 -1
  25. package/dist/types.d.ts +14 -4
  26. package/dist/types.js.map +1 -1
  27. package/dist/utils.d.ts +5 -0
  28. package/dist/utils.js +17 -3
  29. package/dist/utils.js.map +1 -1
  30. package/index.ts +105 -37
  31. package/init.ts +28 -19
  32. package/json-schema-validator.ts +16 -2
  33. package/mcp-auth.ts +27 -2
  34. package/mcp-code.ts +55 -28
  35. package/mcp-panel.ts +6 -5
  36. package/mcp-script-wasm.ts +24 -0
  37. package/mcp-script-worker.mjs +228 -116
  38. package/mcp-setup-panel.ts +9 -10
  39. package/mcp-status.ts +8 -1
  40. package/metadata-cache.ts +1 -1
  41. package/namespace-tools.ts +5 -1
  42. package/package-mcp-loader.ts +21 -6
  43. package/package.json +6 -2
  44. package/project-server-trust.ts +199 -0
  45. package/prompts.ts +5 -5
  46. package/proxy-modes.ts +36 -30
  47. package/semantic-search.ts +1 -1
  48. package/server-manager.ts +6 -3
  49. package/state.ts +5 -1
  50. package/tool-result-renderer.ts +99 -6
  51. package/types.ts +14 -3
  52. package/ui-session.ts +60 -27
  53. package/utils.ts +22 -3
package/CHANGELOG.md CHANGED
@@ -7,6 +7,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.0.0] - 2026-09-26
11
+
12
+ ### Highlights
13
+
14
+ - The adapter now has its own config file, `mcp-adapter.json`, so it can run alongside Pi's upcoming built-in MCP support without starting the same servers twice. If you used `mcp.json` with the adapter, rename it (see Breaking).
15
+ - Opening a repository no longer starts its MCP servers on its own. Project servers wait until you trust the project and approve each server.
16
+ - `mcpScript` code now runs in a QuickJS sandbox that scripts cannot escape to reach your files or processes.
17
+ - MCP servers can now match each request to the Pi tool call that made it.
18
+
19
+ ### Breaking
20
+
21
+ - The adapter no longer reads `<Pi agent dir>/mcp.json` or `.pi/mcp.json`. Those files now belong to Pi's built-in MCP support. Rename yours to `mcp-adapter.json` in the same folder. The format is the same, so `mv` is enough; if `mcp-adapter.json` already exists, merge the two. Until you do, Pi shows a warning with the exact command. `.mcp.json`, `~/.config/mcp/mcp.json`, and `--mcp-config` work as before.
22
+ - The interactive command is now `/mcp-adapter`. `/mcp` still works as a shortcut when Pi's built-in MCP extension is not installed.
23
+
24
+ ### Security
25
+
26
+ - `mcpScript` now runs scripts in a memory-limited QuickJS/WASM sandbox instead of Node's `vm` module, which scripts could escape to reach `process`, the filesystem, or child processes ([#676](https://github.com/nicobailon/pi-mcp-adapter/issues/676)). Each script can emit up to 16 MiB of output, and error messages are capped at 64 KiB. Values pass between the script and Pi as JSON, so values that are not plain JSON still show up but may be formatted differently than before.
27
+ - MCP servers defined by a project no longer start until the project is trusted and you approve the server. This covers `.mcp.json`, `.pi/mcp-adapter.json`, and servers a project brings in through imports, plugins, repo-local host configs, or Pi packages in its settings. In an untrusted project they stay blocked. In a trusted interactive session, Pi shows the server's command or URL and asks once; the approval is saved, and Pi asks again if the server definition changes. Headless sessions skip unapproved servers unless your user-global config sets `settings.projectServers` to `"allow"`. `/mcp-adapter status` shows why a server is blocked. Fixes [#675](https://github.com/nicobailon/pi-mcp-adapter/issues/675).
28
+
29
+ ### Added
30
+
31
+ - MCP tool calls now include the id of the Pi tool call that made them, under `_meta["pi-mcp-adapter/toolCallId"]`, so servers can match requests to Pi's tool calls in their logs and traces. Direct tools, the `mcp` tool, and `mcp__<server>` tools send it. `mcpScript` calls do not, because a script is not a single tool call. Thanks to [@sebavalaris](https://github.com/sebavalaris) for [PR #673](https://github.com/nicobailon/pi-mcp-adapter/pull/673).
32
+
33
+ ## [2.38.0] - 2026-09-26
34
+
35
+ ### Highlights
36
+
37
+ - Search-mode tools become full direct tools after a successful proxy call, without requiring a separate search first.
38
+ - Runtime-registered keep-alive servers now publish their tools even when Pi starts with no enabled MCP servers.
39
+ - Compact `mcpScript` results show which tools ran, how often they ran, and how many calls failed.
40
+ - Stdio configurations support home-relative paths, and MCP UI windows can open in Orca.
41
+ - OpenCode v2 imports, OAuth credential access, and Rust MCP schemas are more reliable.
42
+
43
+ ### Added
44
+
45
+ - A successful `mcp({ tool })` call now activates a held `directTools: "search"` tool, so later calls use its full schema even if the model skipped search. Thanks to [@chiptoe-svg](https://github.com/chiptoe-svg) for [PR #670](https://github.com/nicobailon/pi-mcp-adapter/pull/670).
46
+ - MCP stdio server commands, arguments, and working directories now support home-relative paths. Thanks to [@FRFlo](https://github.com/FRFlo) for [PR #655](https://github.com/nicobailon/pi-mcp-adapter/pull/655).
47
+ - Set `MCP_UI_VIEWER=orca` to open MCP UI windows in Orca. Thanks to [@jaesimio](https://github.com/jaesimio) for [PR #654](https://github.com/nicobailon/pi-mcp-adapter/pull/654).
48
+
49
+ ### Fixed
50
+
51
+ - Keep-alive servers registered at runtime now connect and publish their tools even when no configured servers are enabled at startup. Thanks to [@ahodges22](https://github.com/ahodges22) for [issue #671](https://github.com/nicobailon/pi-mcp-adapter/issues/671).
52
+ - Valid `ancestorConfigRoots` entries that do not contain the current working directory are ignored without warnings. Invalid entries still warn. Thanks to [@TheEdgeOfRage](https://github.com/TheEdgeOfRage) for [issue #668](https://github.com/nicobailon/pi-mcp-adapter/issues/668) and [PR #669](https://github.com/nicobailon/pi-mcp-adapter/pull/669).
53
+ - Collapsed `mcpScript` results now show the tools called, repeat counts, and a visible failure count instead of only the first output line. Unsafe or ambiguous tool names are quoted and escaped, and script code remains hidden. Thanks to [@sargismarkosyan](https://github.com/sargismarkosyan) for [PR #666](https://github.com/nicobailon/pi-mcp-adapter/pull/666).
54
+ - Metadata refreshes no longer reactivate an `mcp` gateway tool removed by the host. On hosts without `unregisterTool`, the adapter can still hide the gateway when direct tools cover the server and restore it when needed. Thanks to [@xulongwu4](https://github.com/xulongwu4) for [PR #665](https://github.com/nicobailon/pi-mcp-adapter/pull/665).
55
+ - `mcpScript` no longer asks models to load its intentionally hidden manual skill. Thanks to [@k03mad](https://github.com/k03mad) for [#659](https://github.com/nicobailon/pi-mcp-adapter/issues/659).
56
+ - OAuth credential reads now reuse a healthy keyring Entry without retaining secret values, avoiding repeated native sessions while still observing external updates. Thanks to [@mmarabel](https://github.com/mmarabel) for [#657](https://github.com/nicobailon/pi-mcp-adapter/issues/657).
57
+ - Suppressing MCP UI windows with `MCP_UI_VIEWER=none` / `off` / `disabled` no longer prints raw output into the TUI. Thanks to [@andreafspeziale](https://github.com/andreafspeziale) for [#656](https://github.com/nicobailon/pi-mcp-adapter/issues/656).
58
+ - The published package now includes the OAuth guide linked from the README. Thanks to [@dajiaohuang](https://github.com/dajiaohuang) for [PR #653](https://github.com/nicobailon/pi-mcp-adapter/pull/653).
59
+ - OpenCode v2 configs now import. Servers under `mcp.servers` are picked up, `disabled: true` servers are skipped, and the snake_case OAuth fields `client_id`, `client_secret`, and `auth_server_metadata_url` are mapped. OpenCode v1 configs keep working. Thanks to [@sleroq](https://github.com/sleroq) for [PR #650](https://github.com/nicobailon/pi-mcp-adapter/pull/650).
60
+ - Tools from Rust MCP servers, such as DBX, no longer print Ajv `unknown format "uint64" ignored` warnings on every call. Number formats like `uint64`, `uint32`, `uint`, and `uint8` are now recognized, and `type`/`minimum` still validate the values. Thanks to [@nightlitten](https://github.com/nightlitten) for [#649](https://github.com/nicobailon/pi-mcp-adapter/issues/649).
61
+
10
62
  ## [2.37.0] - 2026-09-23
11
63
 
12
64
  ### Highlights
@@ -722,7 +774,7 @@ The ranked search scoring, did-you-mean suggestions, approval patterns, endpoint
722
774
  - Added a dedicated Pi-owned onboarding state file so shared-config hints behave as one-time guidance instead of repeating every session.
723
775
 
724
776
  ### Changed
725
- - Updated config precedence to prefer shared MCP files first, then Pi overrides, with `.pi/mcp.json` acting as the final Pi-specific project override.
777
+ - At the time, updated config precedence to prefer shared MCP files first, with `.pi/mcp.json` as the final project override. This legacy layout is superseded by the `mcp-adapter.json` hard cutover documented above.
726
778
  - Updated Claude Code compatibility probing to prefer modern Claude MCP config locations before legacy paths.
727
779
  - Updated project scaffolding so generated `.mcp.json` files are safe minimal shells instead of fake placeholder servers that fail on first reload.
728
780
  - Updated the setup panel and README for clearer first-run guidance, improved spacing, and a more digestible shared-MCP-first setup story.
package/OAUTH.md ADDED
@@ -0,0 +1,369 @@
1
+ # OAuth 2.1 Authentication for MCP
2
+
3
+ This document describes the OAuth 2.1 + PKCE authentication implementation for the Pi MCP Adapter using the official MCP SDK.
4
+
5
+ ## Overview
6
+
7
+ The Pi MCP Adapter uses the official MCP SDK's built-in OAuth implementation, which provides:
8
+
9
+ - **Automatic OAuth endpoint discovery** (RFC 9728) - No manual configuration needed
10
+ - **Dynamic Client Registration** (RFC 7591) - The default for URL-only servers when no pre-registered `clientId` is configured and the server supports registration
11
+ - **Client ID Metadata Documents** (SEP-991) - An advanced opt-in that uses an operator-supplied public HTTPS metadata URL as `client_id` when the authorization server opts in
12
+ - **Automatic callback handling** - Built-in HTTP server handles callbacks automatically
13
+ - **Automatic token refresh** - SDK handles token refresh transparently
14
+
15
+ ## Features
16
+
17
+ - **PKCE (S256)** - Mandatory code challenge method for OAuth 2.1
18
+ - **Automatic Callback Server** - Local browser redirects automatically when available
19
+ - **Manual Remote Flow** - Copy auth URLs and pasted redirect URLs/codes for headless SSH sessions
20
+ - **Dynamic Client Registration** - Registers by default when no pre-registered client is configured and the server supports registration
21
+ - **Client ID Metadata Documents** - Opts into a configured, operator-hosted URL-based client ID when the authorization server advertises support
22
+ - **Auto-Discovery** - Discovers OAuth endpoints from server metadata
23
+ - **Automatic Token Refresh** - SDK handles expired tokens automatically
24
+ - **State Parameter Validation** - CSRF protection
25
+ - **Secure Token Storage** - Persistent OAuth entries are stored in the operating system credential store
26
+
27
+ ## Configuration
28
+
29
+ ### Minimal Configuration (Recommended)
30
+
31
+ For most MCP servers, you only need the URL:
32
+
33
+ ```json
34
+ {
35
+ "mcpServers": {
36
+ "my-oauth-server": {
37
+ "url": "https://api.example.com/mcp"
38
+ }
39
+ }
40
+ }
41
+ ```
42
+
43
+ OAuth is automatically enabled for HTTP servers. The SDK will:
44
+ - Auto-detect if the server requires OAuth
45
+ - Discover OAuth endpoints from the server
46
+ - Use Dynamic Client Registration when no pre-registered client is configured and the server supports it
47
+ - Handle the entire OAuth flow including callback
48
+
49
+ Pi does not configure or host a Client ID Metadata Document by default. URL-only configurations continue to use Dynamic Client Registration. CIMD is available only through the advanced, operator-supplied `oauth.clientMetadataUrl` option below.
50
+
51
+ ### Optional Configuration
52
+
53
+ You can optionally provide a pre-registered client:
54
+
55
+ ```json
56
+ {
57
+ "mcpServers": {
58
+ "my-oauth-server": {
59
+ "url": "https://api.example.com/mcp",
60
+ "auth": "oauth",
61
+ "oauth": {
62
+ "clientId": "your-client-id",
63
+ "clientSecret": "your-client-secret",
64
+ "scope": "read write",
65
+ "authorizationParams": { "access_type": "offline", "prompt": "consent" },
66
+ "redirectUri": "http://localhost:3118/callback"
67
+ }
68
+ }
69
+ }
70
+ }
71
+ ```
72
+
73
+
74
+
75
+ ### Configuration Options
76
+
77
+ - `url` - The MCP server URL (required)
78
+ - `auth` - Set to `"oauth"` to force OAuth, `false` to disable, or omit to auto-detect
79
+ - `oauth.grantType` - `"authorization_code"` (default, browser flow) or `"client_credentials"` (non-interactive)
80
+ - `oauth.clientId` - Pre-registered client ID. Takes precedence over `oauth.clientMetadataUrl` when both are configured.
81
+ - `oauth.clientSecret` - Client secret for confidential clients (optional). When `oauth.clientMetadataUrl` is also set, an explicit `oauth.clientId` is required; the explicit client takes precedence.
82
+ - `oauth.clientMetadataUrl` - Advanced opt-in for an operator-supplied public HTTPS Client ID Metadata Document URL with a non-root path. The URL is used as `client_id` when the authorization server advertises `client_id_metadata_document_supported: true`; otherwise Dynamic Client Registration remains the fallback. The document must be publicly fetchable and match this client's metadata, especially `redirect_uris`. The adapter does not provide a default URL or host this document.
83
+ - `oauth.scope` - Requested OAuth scopes (optional)
84
+ - `oauth.authorizationParams` - Extra authorization URL parameters for provider-specific extensions, such as Google's `{ "access_type": "offline", "prompt": "consent" }`. Flow-owned parameters like `client_id`, `redirect_uri`, `scope`, `state`, `code_challenge`, `response_type`, and `resource` cannot be overridden.
85
+ - `oauth.redirectUri` - Browser callback URI to advertise and bind, such as `http://localhost:3118/callback`. Use `{port}` in a loopback URI when the provider permits an OS-assigned RFC 8252 port, for example `http://127.0.0.1:{port}/callback` (optional)
86
+ - `oauth.clientName` - Client display name used for Dynamic Client Registration fallback (optional, defaults to `Pi Coding Agent`)
87
+ - `oauth.clientUri` - Client homepage URI used for Dynamic Client Registration fallback (optional)
88
+ - `oauth.authServerMetadataUrl` - HTTPS OAuth/OIDC authorization-server metadata document to use authoritatively when MCP protected-resource discovery is unavailable (optional; issuer validation remains enabled)
89
+ - `oauth.skipIssuerMetadataValidation` - Set `true` only for a known-misconfigured authorization server whose metadata issuer cannot be fixed immediately. This weakens OAuth issuer validation.
90
+
91
+ Dynamic fallback clients normally omit `oauth.redirectUri`; the adapter starts the callback server lazily on the default loopback host (`localhost`) and asks the OS for an available local port when auth begins. Use `oauth.redirectUri` when the provider requires a pre-registered callback, such as Slack MCP's Claude-compatible `http://localhost:3118/callback`. A loopback URI must use `http://` with `localhost`, `127.0.0.1`, or `[::1]`. It may contain an explicit port, which is bound exactly, or `{port}`, which is replaced with the OS-assigned port in the authorization and token requests.
92
+
93
+ ### Non-Interactive `client_credentials`
94
+
95
+ For machine-to-machine OAuth, configure `grantType: "client_credentials"`.
96
+
97
+ ```json
98
+ {
99
+ "mcpServers": {
100
+ "my-service": {
101
+ "url": "https://api.example.com/mcp",
102
+ "auth": "oauth",
103
+ "oauth": {
104
+ "grantType": "client_credentials",
105
+ "clientId": "service-client-id",
106
+ "clientSecret": "service-client-secret",
107
+ "scope": "read write"
108
+ }
109
+ }
110
+ }
111
+ }
112
+ ```
113
+
114
+ This flow does not open a browser or use callback handling. `oauth.redirectUri` is ignored for `client_credentials`; `oauth.clientName` and `oauth.clientUri` still apply to dynamic client registration metadata.
115
+
116
+ ## Usage
117
+
118
+ ### Step 1: Authenticate
119
+
120
+ Run the `/mcp-auth` command with the server name:
121
+
122
+ ```
123
+ /mcp-auth my-oauth-server
124
+ ```
125
+
126
+ Manual `/mcp-auth` is the default flow. If you set `settings.autoAuth: true`, proxy/direct tool execution will trigger OAuth automatically when a server returns `needs-auth`, then retry the original operation once.
127
+
128
+ This will:
129
+ 1. Start the callback server lazily on an OS-assigned local port, on an OS-assigned host-specific `{port}` callback, or on the exact `oauth.redirectUri` port for fixed callbacks
130
+ 2. Discover OAuth endpoints automatically
131
+ 3. Use Dynamic Client Registration by default, or the explicitly configured Client ID Metadata Document when supported
132
+ 4. Open your browser for authentication
133
+ 5. Wait for the automatic callback
134
+ 6. Complete the OAuth flow
135
+ 7. Store tokens securely
136
+
137
+ ### Remote/headless authentication
138
+
139
+ When Pi runs over SSH or in a headless environment, use the proxy tool to retrieve the authorization URL instead of relying on OS browser launch:
140
+
141
+ ```
142
+ mcp({ action: "auth-start", server: "my-oauth-server" })
143
+ ```
144
+
145
+ Open the returned URL in your local browser. After approval, copy the full redirected localhost URL from the browser address bar (the page may fail to load locally) and complete the same pending auth flow:
146
+
147
+ ```
148
+ mcp({
149
+ action: "auth-complete",
150
+ server: "my-oauth-server",
151
+ args: { redirectUrl: "http://localhost:19876/callback?code=...&state=..." }
152
+ })
153
+ ```
154
+
155
+ You can also pass only the `code` query parameter with `args: { code: "..." }`. JSON-string args remain supported. Redirect URL completion validates the saved OAuth state; raw code completion is available for providers that display a code directly.
156
+
157
+ ### Step 2: Use the Server
158
+
159
+ Once authenticated, use the server normally:
160
+
161
+ ```
162
+ mcp({ server: "my-oauth-server" })
163
+ mcp({ tool: "my-tool", args: { key: "value" } })
164
+ ```
165
+
166
+ The SDK automatically:
167
+ - Adds the access token to requests
168
+ - Refreshes expired tokens automatically
169
+ - Re-authenticates if tokens are invalid
170
+
171
+ To clear stored OAuth credentials and force a fresh authorization:
172
+
173
+ ```
174
+ /mcp-adapter logout my-oauth-server
175
+ ```
176
+
177
+ Within one Pi process, logout is a linearizable boundary: OAuth work that began
178
+ before logout cannot recreate credentials after they are cleared, and new OAuth
179
+ work is admitted after logout finishes. Explicit token updates made through the
180
+ public API retain last-writer semantics. Separate Pi processes are intentionally
181
+ not coordinated, so concurrent cross-process credential operations can still race.
182
+
183
+ ## How It Works
184
+
185
+ ### Authentication Flow
186
+
187
+ ```
188
+ ┌─────────┐ ┌──────────────┐ ┌─────────────────┐
189
+ │ Pi │────▶│ MCP Server │────▶│ OAuth Server │
190
+ │ │ │ │ │ │
191
+ │ 1. Init │ │ 2. Discovery │ │ 3. Register │
192
+ │ │ │ │ │ │
193
+ │ │◀────│ │◀────│ 4. Auth URL │
194
+ │ │ │ │ │ │
195
+ │ │────▶│ Callback │◀────│ 5. Browser │
196
+ │ │ │ Server │ │ Redirect │
197
+ │ │ │ │ │ │
198
+ │ │◀────│ │◀────│ 6. Code │
199
+ │ │ │ │ │ │
200
+ │ │────▶│ │────▶│ 7. Exchange │
201
+ │ │ │ │ │ │
202
+ │ │◀────│ │◀────│ 8. Tokens │
203
+ └─────────┘ └──────────────┘ └─────────────────┘
204
+ ```
205
+
206
+ ### Auto-Discovery
207
+
208
+ The SDK attempts to discover OAuth endpoints using:
209
+
210
+ 1. **RFC 9728 Metadata** - Fetches `/.well-known/oauth-protected-resource`
211
+ 2. **WWW-Authenticate Header** - Parses `resource_metadata` from 401 responses
212
+
213
+ ### Client ID Metadata Documents and Dynamic Registration
214
+
215
+ CIMD is an advanced, explicit opt-in. Set `oauth.clientMetadataUrl` to a stable, operator-supplied public HTTPS URL that serves this client's OAuth metadata. When authorization-server discovery advertises `client_id_metadata_document_supported: true`, the adapter and SDK use that URL directly as `client_id` and skip Dynamic Client Registration. The URL must have a non-root path. An explicit `oauth.clientId` takes precedence. Combining `oauth.clientMetadataUrl` with `oauth.clientSecret` without an explicit `oauth.clientId` is rejected.
216
+
217
+ The adapter does not provide a default URL or host the public document: operators must publish it and keep fields such as `redirect_uris`, `grant_types`, `response_types`, and `token_endpoint_auth_method` consistent with the configured flow. URL-only/default Pi configurations therefore continue to use Dynamic Client Registration. When the server does not advertise CIMD support, or no metadata URL is configured, the SDK uses Dynamic Client Registration if the server supports it:
218
+
219
+ 1. Discovers the registration endpoint from OAuth metadata
220
+ 2. Registers a new client with:
221
+ - `client_name`: configured `oauth.clientName` or "Pi Coding Agent"
222
+ - `client_uri`: configured `oauth.clientUri` or the adapter repository URL
223
+ - `redirect_uris`: `["http://localhost:<active-callback-port>/callback"]`, or the configured `oauth.redirectUri`
224
+ - `grant_types`: `["authorization_code", "refresh_token"]`
225
+ 3. Stores the registered client credentials and the redirect URIs returned by the authorization server
226
+
227
+ When a fresh browser auth starts, cached dynamic fallback client info with tokens is re-registered if its stored redirect URIs are missing or do not include the current redirect URI. Token refresh does not perform this redirect check, so existing refresh-token grants keep working even after a callback setting changes.
228
+
229
+ ### Callback Server
230
+
231
+ A Node.js HTTP server runs on a loopback callback endpoint and handles the active callback path:
232
+
233
+ - Dynamic registration starts the callback server only when auth begins, binds the default host `localhost`, and asks the OS for an available local port
234
+ - Pre-registered clients (`oauth.clientId`) without `oauth.redirectUri` require the exact configured callback port from `MCP_OAUTH_CALLBACK_PORT` or the default `19876` on `localhost`
235
+ - `oauth.redirectUri` binds the exact loopback host and path. An explicit port is bound exactly; `{port}` asks the OS for a port and is replaced with that assigned value before the URI is advertised to the provider
236
+
237
+ - Handles `code`, `state`, and `error` parameters
238
+ - Displays success/error HTML pages
239
+ - Validates state parameter for CSRF protection
240
+ - Has a 5-minute timeout for pending authorizations
241
+
242
+ ## Token Storage
243
+
244
+ Persistent OAuth entries are stored per configured server name in the operating system credential store, using macOS Keychain, Windows Credential Manager, or Linux Secret Service/libsecret through `@napi-rs/keyring`. The stored entry contains tokens, dynamic client information, legacy verifier/state fields when present, and the server URL binding.
245
+
246
+ Windows Credential Manager cannot hold a typical large OAuth JSON blob in one value, so payloads over 1,000 UTF-16 code units are stored as a manifest plus chunks; the size-limited test store uses the same representation. macOS Keychain and Linux Secret Service keep each record in one item, including ordinary 8–10 KiB records; if an unusually large record exceeds the native store's actual limit, that store error is surfaced. This avoids separate prompts for digest-addressed Keychain chunks. On macOS and Linux, the first ordinary read of a previously chunked record validates and rewrites it as one item before cleaning up its old chunks. Windows and the size-limited test store retain the chunked representation. Status inspection reads the existing representation but does not compact it; existing secure-record and legacy-plaintext cleanup semantics still apply.
247
+
248
+ The adapter fails closed when the OS credential store is unavailable. On headless Linux, configure an unlocked Secret Service-compatible keyring before using persistent OAuth; the adapter does not silently fall back to plaintext token files. Windows OpenSSH network logons may report `ERROR_NO_SUCH_LOGON_SESSION` (1312) because Credential Manager has no credential set for that logon.
249
+
250
+ For Windows OpenSSH/headless use, `settings.oauthCredentialStore: "encrypted-file"` explicitly selects an AES-256-GCM file store. It requires `PI_MCP_ADAPTER_OAUTH_FILE_KEY` to contain canonical base64 for exactly 32 random bytes; generate one with `node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"` and inject it through an external secret mechanism. Never place the key in config or beside the ciphertext. One authenticated, versioned envelope is stored per hashed server account at `<Pi agent directory>/mcp-oauth-encrypted/sha256-<server-hash>/credentials.json`. The server URL and secrets appear only inside ciphertext, and account-bound authenticated data prevents copying an envelope to another account.
251
+
252
+ Encrypted-file writes use private directory/file modes where supported and same-directory atomic replacement. POSIX modes are checked on reads, but they do not establish a Windows ACL; encryption with the external key is the confidentiality boundary. This backend never falls back to the OS store, reads `oauthDir` / `MCP_OAUTH_DIR`, or imports legacy plaintext. Reauthenticate after opting in. Key loss or rotation makes existing envelopes unreadable; remove them and reauthenticate with the new key.
253
+
254
+ On Linux, if credential access fails because Pi inherited a revoked session keyring, the adapter makes one best-effort retry through `keyctl session - node <packaged helper>`. This lets explicit re-authentication write fresh credentials from a new session keyring without restarting a long-lived tmux or server process. The recovery path requires `keyctl` and `node` on `PATH`; missing, locked, or otherwise unavailable credential stores still fail closed.
255
+
256
+ Complete credential entries are held in memory for the lifetime of the Pi process on every supported credential-store platform. The MCP SDK reads the access token before every outbound request, so caching avoids a credential-store lookup on each tool call; on Linux this specifically avoids overloading the Secret Service daemon. The cache is filled on the first read for a server and covers both present and absent entries. Authenticating, refreshing, and logging out all update it immediately, so credential changes made through Pi take effect at once. Status-panel inspection deliberately bypasses it and still reads the store directly.
257
+
258
+ A credential changed or deleted by another process while Pi is running is not observed immediately. The affected server picks it up after the first credential-backed authentication failure in that `needs-auth` episode: Pi discards the cached entry, and the following read reloads from the credential store. Restarting Pi also clears the cache. Set `PI_MCP_ADAPTER_DISABLE_AUTH_CACHE=1` to turn the cache off entirely and restore a credential-store read per request.
259
+
260
+ Older versions stored plaintext entries at `~/.pi/agent/mcp-oauth/sha256-<server-hash>/tokens.json`, or under `settings.oauthDir` / `MCP_OAUTH_DIR`. With the default OS backend, the first read after upgrade imports a valid legacy entry and removes the plaintext `tokens.json`. The encrypted-file backend leaves legacy files untouched. These directories are legacy import locations, not persistent credential stores or isolation namespaces.
261
+
262
+ The stored `serverUrl` field ensures credentials are invalidated if the server URL changes.
263
+
264
+ ## Security Considerations
265
+
266
+ ### PKCE
267
+
268
+ All OAuth flows use PKCE with the S256 method, preventing authorization code interception attacks.
269
+
270
+ ### State Parameter
271
+
272
+ A cryptographically secure random state parameter is generated for each flow and validated on callback.
273
+
274
+ ### Issuer Metadata Validation
275
+
276
+ OAuth authorization-server metadata normally must echo the expected issuer. This protects against authorization-server mix-up. The adapter keeps this check on by default.
277
+
278
+ For private servers with known-broken metadata, `oauth.skipIssuerMetadataValidation: true` forwards the SDK's issuer-validation opt-out for that server only. Use it only as a temporary workaround while the server metadata is fixed. Do not use it for public or untrusted servers.
279
+
280
+ When an MCP server does not publish usable protected-resource metadata, configure `oauth.authServerMetadataUrl` with the HTTPS URL of its OAuth/OIDC authorization-server metadata document. That document is authoritative instead of MCP protected-resource discovery, and its issuer is still checked by default. Treat this as trusted configuration and point it only at a metadata endpoint you explicitly trust.
281
+
282
+ ### Credential Stores
283
+
284
+ Persistent OAuth credentials are written to the OS credential store by default, or only to the encrypted file store when explicitly selected. Legacy plaintext files are read only for one-way migration to the default OS store and are removed after successful import. On Linux, revoked session-keyring errors can be retried once through a fresh `keyctl session` helper during explicit re-authentication.
285
+
286
+ Credential entries reside in process memory for the lifetime of the Pi process rather than being re-read per request, and the process-memory copy is discarded on exit.
287
+
288
+ ### URL Validation
289
+
290
+ Credentials are tied to a specific server URL. If the URL changes, the credentials are invalidated and re-authentication is required.
291
+
292
+ ## Troubleshooting
293
+
294
+ ### "No OAuth tokens found"
295
+
296
+ Run `/mcp-auth <server>` to authenticate.
297
+
298
+ ### "Failed to discover OAuth endpoints"
299
+
300
+ The SDK automatically discovers OAuth endpoints from the MCP server. If discovery fails, the server may require a pre-registered client ID:
301
+
302
+ ```json
303
+ {
304
+ "mcpServers": {
305
+ "server": {
306
+ "url": "https://api.example.com/mcp",
307
+ "auth": "oauth",
308
+ "oauth": {
309
+ "clientId": "your-client-id",
310
+ "scope": "read"
311
+ }
312
+ }
313
+ }
314
+ }
315
+ ```
316
+
317
+ ### "Dynamic client registration not supported"
318
+
319
+ Some servers require pre-registered clients. Obtain a client ID from your OAuth provider and add it to the config.
320
+
321
+ ### Callback server already in use
322
+
323
+ Dynamic fallback browser OAuth uses a lazy OS-assigned port on the default loopback host (`localhost`), so the configured default port being busy should not block fallback registration.
324
+
325
+ For pre-registered OAuth clients (`oauth.clientId`), the callback redirect URI must match the provider registration policy. Set `oauth.redirectUri` to the full fixed callback, such as Slack MCP's Claude-compatible `http://localhost:3118/callback`, use a loopback `{port}` URI when the provider explicitly permits dynamic RFC 8252 ports, or free/set `MCP_OAUTH_CALLBACK_PORT` when you rely on the default `/callback` path without an explicit redirect URI.
326
+
327
+ ### Browser doesn't open
328
+
329
+ If the browser fails to open (e.g., in SSH sessions), the authorization URL will be displayed. Copy it manually to your browser.
330
+
331
+ ## Architecture
332
+
333
+ The OAuth implementation uses the following modules:
334
+
335
+ - `mcp-auth.ts` - Auth storage and retrieval through the OS credential store, with one-way legacy `tokens.json` import
336
+ - `mcp-oauth-provider.ts` - SDK OAuthClientProvider implementation
337
+ - `mcp-callback-server.ts` - Node.js HTTP callback server
338
+ - `mcp-auth-flow.ts` - High-level auth flow using SDK transport
339
+
340
+ ## SDK Integration
341
+
342
+ The implementation uses the stable modular MCP client and OAuth APIs:
343
+
344
+ ```typescript
345
+ import {
346
+ auth,
347
+ StreamableHTTPClientTransport,
348
+ UnauthorizedError,
349
+ type OAuthClientProvider,
350
+ } from "@modelcontextprotocol/client"
351
+ ```
352
+
353
+ The `McpOAuthProvider` class implements `OAuthClientProvider` and is passed to `StreamableHTTPClientTransport`:
354
+
355
+ ```typescript
356
+ const transport = new StreamableHTTPClientTransport(url, {
357
+ authProvider: new McpOAuthProvider(serverName, serverUrl, config, callbacks),
358
+ })
359
+ ```
360
+
361
+ ## References
362
+
363
+ - [MCP SDK Documentation](https://github.com/modelcontextprotocol/typescript-sdk)
364
+ - [MCP Authorization Specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization)
365
+ - [OAuth 2.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-11)
366
+ - [PKCE (RFC 7636)](https://datatracker.ietf.org/doc/html/rfc7636)
367
+ - [OAuth Client ID Metadata Document](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00)
368
+ - [Dynamic Client Registration (RFC 7591)](https://datatracker.ietf.org/doc/html/rfc7591)
369
+ - [OAuth Protected Resource Metadata (RFC 9728)](https://datatracker.ietf.org/doc/html/rfc9728)