pi-mcp-adapter 2.36.0 → 2.38.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.
- package/CHANGELOG.md +55 -0
- package/OAUTH.md +369 -0
- package/README.md +51 -14
- package/cli.js +33 -22
- package/commands.ts +3 -3
- package/config.ts +40 -9
- package/direct-tool-surface.ts +1 -1
- package/dist/config.js +42 -9
- package/dist/config.js.map +1 -1
- package/dist/jev-client.d.ts +1 -2
- package/dist/jev-client.js +59 -32
- package/dist/jev-client.js.map +1 -1
- package/dist/jev-contracts.d.ts +1 -1
- package/dist/jev-key-store.d.ts +33 -4
- package/dist/jev-key-store.js +148 -28
- package/dist/jev-key-store.js.map +1 -1
- package/dist/json-schema-validator.js +15 -2
- package/dist/json-schema-validator.js.map +1 -1
- package/dist/mcp-auth-flow.js +1 -2
- package/dist/mcp-auth-flow.js.map +1 -1
- package/dist/mcp-auth.d.ts +2 -0
- package/dist/mcp-auth.js +27 -2
- package/dist/mcp-auth.js.map +1 -1
- package/dist/metadata-cache.js +1 -1
- package/dist/metadata-cache.js.map +1 -1
- package/dist/server-manager.js +6 -4
- package/dist/server-manager.js.map +1 -1
- package/dist/types.d.ts +9 -3
- package/dist/types.js.map +1 -1
- package/dist/utils.d.ts +2 -0
- package/dist/utils.js +10 -3
- package/dist/utils.js.map +1 -1
- package/index.ts +88 -58
- package/init.ts +14 -15
- package/jev-client.ts +58 -31
- package/jev-contracts.ts +2 -2
- package/jev-key-store.ts +144 -31
- package/json-schema-validator.ts +16 -2
- package/mcp-auth-flow.ts +1 -2
- package/mcp-auth.ts +27 -2
- package/mcp-code.ts +6 -6
- package/metadata-cache.ts +1 -1
- package/package.json +7 -6
- package/proxy-modes.ts +1 -1
- package/semantic-search.ts +3 -3
- package/server-manager.ts +6 -3
- package/tool-result-renderer.ts +99 -6
- package/types.ts +9 -3
- package/ui-session.ts +60 -27
- package/utils.ts +11 -3
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,61 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.38.0] - 2026-09-26
|
|
11
|
+
|
|
12
|
+
### Highlights
|
|
13
|
+
|
|
14
|
+
- Search-mode tools become full direct tools after a successful proxy call, without requiring a separate search first.
|
|
15
|
+
- Runtime-registered keep-alive servers now publish their tools even when Pi starts with no enabled MCP servers.
|
|
16
|
+
- Compact `mcpScript` results show which tools ran, how often they ran, and how many calls failed.
|
|
17
|
+
- Stdio configurations support home-relative paths, and MCP UI windows can open in Orca.
|
|
18
|
+
- OpenCode v2 imports, OAuth credential access, and Rust MCP schemas are more reliable.
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
|
|
22
|
+
- 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).
|
|
23
|
+
- 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).
|
|
24
|
+
- 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).
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
|
|
28
|
+
- 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).
|
|
29
|
+
- 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).
|
|
30
|
+
- 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).
|
|
31
|
+
- 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).
|
|
32
|
+
- `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).
|
|
33
|
+
- 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).
|
|
34
|
+
- 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).
|
|
35
|
+
- 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).
|
|
36
|
+
- 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).
|
|
37
|
+
- 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).
|
|
38
|
+
|
|
39
|
+
## [2.37.0] - 2026-09-23
|
|
40
|
+
|
|
41
|
+
### Highlights
|
|
42
|
+
|
|
43
|
+
- Use Jev semantic search with other System One providers, such as OpenCode Zen, Command Code, or OpenRouter, by setting `SYSTEMONE_ENDPOINT`.
|
|
44
|
+
- Stop agents from installing new MCP servers with `settings.allowInstall: false`.
|
|
45
|
+
- Turn off resource tools for every server with one `settings.exposeResources: false` setting.
|
|
46
|
+
- Start Pi without waiting on MCP servers even when cached tool metadata is missing, with `settings.deferWithMissingMetadata`.
|
|
47
|
+
|
|
48
|
+
### Added
|
|
49
|
+
|
|
50
|
+
- Jev can send System One requests to any HTTPS provider endpoint set in `SYSTEMONE_ENDPOINT`. TypeSafe stays the default. API keys are stored per endpoint, and an invalid endpoint turns Jev off instead of quietly falling back to TypeSafe. Thanks to [@jagaliano](https://github.com/jagaliano) for [PR #645](https://github.com/nicobailon/pi-mcp-adapter/pull/645).
|
|
51
|
+
- `settings.deferWithMissingMetadata: true` lets Pi start without connecting to MCP servers even when their cached metadata is missing or out of date. Those servers show no tools until the first MCP call loads them. Thanks to [@j62268781-alt](https://github.com/j62268781-alt) for [#641](https://github.com/nicobailon/pi-mcp-adapter/issues/641).
|
|
52
|
+
- `settings.allowInstall: false` blocks agents from installing remote MCP servers with `mcp({ action: "install" })`, for headless or locked-down setups. Thanks to [@gastmaier](https://github.com/gastmaier) for [#638](https://github.com/nicobailon/pi-mcp-adapter/issues/638).
|
|
53
|
+
- `settings.exposeResources: false` hides resource tools for every server. A server's own `exposeResources` setting still wins. Thanks to [@rakesh-vs](https://github.com/rakesh-vs) for [PR #636](https://github.com/nicobailon/pi-mcp-adapter/pull/636).
|
|
54
|
+
|
|
55
|
+
### Changed
|
|
56
|
+
|
|
57
|
+
- The Jev key command is now `pi-mcp-adapter key set systemone`, and the environment variable is `SYSTEMONE_API_KEY`. The old `key set typesafe` command still works, and `TYPESAFE_API_KEY` still works with the default TypeSafe endpoint.
|
|
58
|
+
- Supports Pi 0.87.
|
|
59
|
+
|
|
60
|
+
### Fixed
|
|
61
|
+
|
|
62
|
+
- `getMcpOAuthTokensForUrl` no longer returns an expired access token when no refresh token is stored, so other extensions see a signed-out server instead of sending a dead token. Thanks to [@benjaminsirb](https://github.com/benjaminsirb) for [#644](https://github.com/nicobailon/pi-mcp-adapter/issues/644).
|
|
63
|
+
- Tools in `directTools: "search"` mode now stay inactive until a search selects them, even if another extension turns them back on. Tools a search activates stay on until the session ends. Thanks to [@VoidInTheShell](https://github.com/VoidInTheShell) for [PR #640](https://github.com/nicobailon/pi-mcp-adapter/pull/640).
|
|
64
|
+
|
|
10
65
|
## [2.36.0] - 2026-09-21
|
|
11
66
|
|
|
12
67
|
### Highlights
|
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 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)
|