passcontrol 0.1.2 → 0.2.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/README.md CHANGED
@@ -1,183 +1,112 @@
1
1
  # PassControl
2
2
 
3
- **An identity & credential gateway for AI agents.** Stop pasting your OpenAI / Anthropic /
4
- Groq / Mistral / Together / DeepSeek keys into agent runtimes. Give each agent a cryptographic
5
- **passport**; it signs a challenge to mint a short-lived **work-visa**; the gateway injects your
6
- *real* provider key from a vault and proxies the call — so **the agent never holds the key**.
7
- You get per-agent budgets, capability scopes, an instant kill switch, and a per-agent audit trail.
3
+ **An identity & credential gateway for AI agents.** Stop pasting your OpenAI/Anthropic keys
4
+ into agent runtimes. Give each agent a cryptographic **passport**; it signs a challenge to
5
+ mint a short-lived **work-visa**; the gateway injects your *real* provider key from a vault
6
+ and proxies the call — so the agent never holds the key. You get per-agent budgets, scopes,
7
+ an instant kill switch, and a per-agent audit trail.
8
8
 
9
- A [Vertias](https://vertias.eu) project. **Bring-your-own-key** — your provider key stays in your
10
- own vault. Self-host it today; a managed version comes later.
9
+ A [Vertias](https://vertias.eu) project. **Bring-your-own-key** (you keep your provider key);
10
+ self-host it, or use the managed version when it's available.
11
11
 
12
12
  > ⚠️ **Status: early.** Built by a small team, **not yet independently audited.** It's
13
- > security-focused and test-covered, but treat it as beta — run it against a **non-critical key
14
- > first**, and see [Security](#security) for responsible disclosure. We'd rather you know than
13
+ > security-focused and test-covered, but treat it as beta — run it on a non-critical key
14
+ > first, and see [Security](#security) for responsible disclosure. We'd rather you know than
15
15
  > find out.
16
16
 
17
- **New here?** The [Getting Started tutorial](./TUTORIAL.md) takes you from install to a real
18
- governed agent in ~15 minutes.
19
-
20
- ```bash
21
- npm install -g passcontrol
22
- passcontrol setup # boots the self-hostable stack + opens the Control Tower
23
- ```
24
-
25
17
  ---
26
18
 
27
19
  ## Why
28
-
29
- A raw provider key handed to an autonomous agent **leaks** (logs, repos, prompts), **never
30
- rotates**, has **no per-agent spend cap**, **no off-switch**, and leaves **no record** of which
31
- agent did what. PassControl takes the key out of the agent entirely and puts a governed gateway
32
- in front of it.
20
+ A raw provider key handed to an autonomous agent leaks (logs, repos, prompts), never rotates,
21
+ has no per-agent spend cap, no off-switch, and no record of *which* agent did *what*.
22
+ PassControl removes the key from the agent entirely and puts a governed gateway in front.
33
23
 
34
24
  ## How it works
35
-
36
- 1. **Passport** — each agent holds only an Ed25519 private key. It *only ever signs*; the key
37
- never travels over the wire.
38
- 2. **Work-visa** — the agent signs a challenge (timestamp + single-use nonce) and mints a
39
- short-lived (~5 min) token carrying its identity, scope, and budget snapshot.
40
- 3. **Inject & proxy** — a request arrives bearing a visa. The gateway verifies it → checks the
41
- kill switch → checks scope (provider + model **and** endpoint) → reserves budget atomically →
42
- pulls your provider key from the vault → injects it → forwards to the provider and streams
43
- back. The agent never sees the key.
44
- 4. **Govern** — per-agent **token + dollar** budgets (enforced *before* the call), a layered kill
45
- switch (platform / tenant / per-agent), and an append-only audit log of every call.
46
-
47
- ```
48
- agent ──sign──▶ challenge ──visa──▶ ┌─────────── PassControl gateway ───────────┐
49
- │ verify · kill/scope/budget · inject key │ ──▶ provider
50
- (holds only a passport key) │ (real key from vault, never returned) │ ◀── stream
51
- └────────────────────────────────────────────┘
52
- ```
25
+ 1. **Passport** — each agent holds only an Ed25519 private key; it *only ever signs*, never travels.
26
+ 2. **Work-visa** — the agent signs a challenge (timestamp + single-use nonce) → mints a
27
+ short-lived (5 min) HS256 token carrying its identity, scope, and budget.
28
+ 3. **Inject & proxy** — a request arrives with a visa; the gateway verifies it → checks the
29
+ kill switch → checks scope → reserves budget → pulls your provider key from Supabase Vault
30
+ → injects it → forwards to the provider and streams back. The agent never sees the key.
31
+ 4. **Govern** — per-agent token/cost budgets (enforced), layered kill switch
32
+ (platform / tenant / per-agent), and an append-only audit log of every call.
53
33
 
54
34
  ## Features
55
-
56
- - 🔑 **Agents never hold your provider key** — BYOK; the key stays vaulted, injected in-flight only
57
- - 🪪 **Per-agent cryptographic identity** (Ed25519) with short-lived, revocable visas
58
- - 💸 **Enforced per-agent token + cost (USD) budgets** — reserved pre-flight, reconciled after
59
- - 🎯 **Capability scoping** — a visa is scoped to specific models *and* endpoints, so a
60
- chat-scoped agent can't reach files, fine-tuning, batches, embeddings, etc. with your key
61
- - ⛔ **Instant, layered kill switch** + per-agent suspend/revoke — stop a running agent mid-task
62
- - 📒 **Append-only audit trail** per agent/passport (direct `UPDATE`/`DELETE`/`TRUNCATE` rejected
63
- by the database)
64
- - 🧰 **Drop-in for your SDK** (OpenAI, Anthropic, and OpenAI-compatible Groq / Mistral / Together /
65
- DeepSeek) — **or any agent** via the visa sidecar (OpenHands, Aider, Cline, Continue…)
66
- - 🖥️ **Control Tower** dashboard (fleet, spend, budgets, audit, kill switch) + a developer
67
- control-plane API + TOTP MFA
68
-
69
- ## Install & first run
70
-
71
- **Global CLI (recommended):**
35
+ - 🔑 Agents never hold your provider key (BYOK; key stays in the vault, injected in-flight)
36
+ - 🪪 Per-agent cryptographic identity (Ed25519), short-lived revocable visas
37
+ - 💸 Enforced per-agent token/cost budgets (reserved pre-flight, reconciled after)
38
+ - ⛔ Layered, per-tenant kill switch + per-agent suspend
39
+ - 📒 Per-agent / per-passport audit trail (append-only; direct `UPDATE` / `DELETE` /
40
+ `TRUNCATE` rejected by the database)
41
+ - 🧰 Drop-in: point your existing OpenAI/Anthropic/OpenAI-compatible SDK at the gateway
42
+ (OpenAI, Anthropic, Groq, Mistral, Together, DeepSeek)
43
+ - 🔌 MCP server: expose governed `chat` / `list_models` tools to Claude Desktop, Cursor &
44
+ Claude Code — same scope, budget, and kill switch (`passcontrol mcp`)
45
+ - 🖥️ Control Tower dashboard + a developer control-plane API + TOTP MFA
46
+
47
+ ## Quickstart (self-host)
48
+ Stack: **Next.js** (App Router, edge routes) · **Supabase** (Postgres + Vault + Auth) ·
49
+ **Upstash Redis**. Deploy on Vercel or any Node host (`next start`). No Vercel-proprietary
50
+ services are required — the kill switch is Redis-backed.
51
+
52
+ ### Local (Docker) quickstart
53
+ For the fastest local run, use the bundled Docker stack. It starts Supabase locally
54
+ (Postgres + Vault + Auth), Redis-over-REST, applies migrations inside the DB container, and
55
+ seeds a confirmed dev user. Prereqs: Docker Desktop and the Supabase CLI. No host `psql`
56
+ is required.
72
57
 
73
58
  ```bash
74
- npm install -g passcontrol
75
- passcontrol --version # 0.1.1
76
- passcontrol setup # prereq checks → fetches the stack → boots it → opens the dashboard
59
+ git clone https://github.com/<you>/passcontrol && cd passcontrol
60
+ npm install
61
+ npm run dev:stack # starts Supabase + Redis locally, migrates, seeds a dev user
62
+ npm run dev:docker # runs the app against the local stack (loads .env.docker)
77
63
  ```
78
64
 
79
- The published npm package is **just the CLI** (a handful of files, no provider keys). `passcontrol
80
- setup` detects the global install and offers to clone the self-hostable stack (Supabase + Redis +
81
- dashboard) into `~/passcontrol`, install its dependencies, and start it — one command from nothing
82
- to a running Control Tower. It first checks your prerequisites (Docker running, Supabase CLI, Node
83
- version, free ports) and tells you exactly what to fix if something's missing.
65
+ > Use **`npm run dev:docker`**, not `npm run dev`, for the local stack — plain `npm run
66
+ > dev` loads `.env.local` (your hosted Supabase), not the Docker stack's `.env.docker`.
84
67
 
85
- - Change the checkout location: `--app-dir <path>` or `PASSCONTROL_APP_ROOT=<path>`
86
- - Non-interactive: `--yes`
87
- - Skip opening the browser: `--no-open`
88
- - Ports already taken by another local Supabase? `passcontrol setup --port-offset 100`
89
- (offsets Supabase + Redis together, e.g. API `54421`, DB `54422`; the dashboard stays on `:3000`)
90
-
91
- Then log in to the Control Tower at **http://localhost:3000** with the seeded local dev user:
68
+ Open `http://localhost:3000` and log in with:
92
69
 
93
70
  ```text
94
71
  dev@passcontrol.local
95
72
  passcontrol-dev
96
73
  ```
97
74
 
98
- > ⚠️ This seeded user exists **only for the local Docker stack** (created by `scripts/seed.mjs`).
99
- > **Never deploy it or reuse these credentials.** Real deployments create accounts through normal
100
- > signup, gated by `INVITE_CODE`; no default credentials ship.
101
-
102
- Add a **non-critical** provider key in the Control Tower, issue a passport, and copy the one-time
103
- `PASSPORT_ID` / `PASSPORT_SECRET`. Then, in your project directory:
75
+ Then add a provider key in the Control Tower, issue a passport, and run:
104
76
 
105
77
  ```bash
106
- passcontrol init # gateway + passport + provider/model → writes .passcontrol
107
- passcontrol doctor --deep # verifies config, prerequisites, and mints a test visa
108
- passcontrol call "Say hello in 3 words"
109
- passcontrol spend # confirms governed spend
78
+ PASSPORT_ID=<passport_id> PASSPORT_SECRET=<passport_secret> \
79
+ node examples/chat-agent.mjs "Say hello in 3 words"
110
80
  ```
111
81
 
112
- You'll see a streamed response and an `ok` row in the dashboard Audit Log — the complete governed
113
- loop: **passport → visa → vault key injection → proxied call → audit**. That last call uses your
114
- real key from the local Vault, so start with a throwaway one.
82
+ The final agent call uses your real Anthropic/OpenAI key from the local Vault, so start
83
+ with a non-critical key.
115
84
 
116
- > Working from a **source clone** instead of the global install? Everything below works as
117
- > `npm run cli -- <command>`; after `npm link` in the clone, the short `passcontrol <command>` form
118
- > works too.
85
+ ### Manual self-host quickstart
119
86
 
120
- ## Real agents & the visa sidecar
121
-
122
- A visa is deliberately short-lived so it's revocable — but a real coding agent runs a **long,
123
- multi-call session** that would outlive a single visa. The **sidecar** solves this: a tiny local
124
- proxy that mints, caches, and auto-refreshes the visa (and re-mints instantly on expiry), so your
125
- agent points at one stable endpoint and **never times out mid-task**.
87
+ > **Supabase specifically** (not vanilla Postgres): the credential vault uses the
88
+ > `supabase_vault` extension, so you need a Supabase project (hosted or the self-hosted
89
+ > Supabase stack), not a plain Postgres database.
126
90
 
127
91
  ```bash
128
- passcontrol sidecar # http://127.0.0.1:8788
129
- passcontrol env openhands # prints ready-to-paste settings for your agent
92
+ git clone https://github.com/<you>/passcontrol && cd passcontrol
93
+ npm install
94
+ cp .env.example .env.local # fill in Supabase / Upstash / secrets
95
+ DATABASE_URL='postgresql://…' npm run migrate # applies db/migrations/*.sql in order, once each
96
+ npm run dev # or build + `next start` on any Node host
130
97
  ```
98
+ See `.env.example` for the full config (Supabase URL/keys, `VISA_SECRET`, `CACHE_ENC_KEY`,
99
+ Upstash, `CRON_SECRET`, `INVITE_CODE`). Apply migrations `0001 → …` in order;
100
+ `db/tests/rls_invariants.sql` checks tenant isolation on your database.
131
101
 
132
- Point any OpenAI/Anthropic-compatible agent at the sidecar with a **dummy** key:
133
-
134
- ```bash
135
- export ANTHROPIC_BASE_URL="http://127.0.0.1:8788/api/v1/anthropic" # or /api/v1/openai, /deepseek…
136
- export ANTHROPIC_API_KEY="passcontrol" # ignored — the sidecar injects a live visa
137
- ```
102
+ **Background reconcile job (required on non-Vercel hosts):** a periodic call to
103
+ `GET /api/cron/reconcile` (with header `Authorization: Bearer $CRON_SECRET`) corrects budget
104
+ drift and flushes last-seen. On Vercel it's wired via `vercel.json`. Self-hosting, schedule it
105
+ yourself (system `cron`, a GitHub Action, etc.) every few minutes — it's a correction layer,
106
+ not the hot path, so an occasional missed run is harmless.
138
107
 
139
- The agent never holds a real key or a long-lived token. Presets ship for **openhands, aider, cline,
140
- continue, litellm** (`passcontrol env <preset>`). A single long streaming completion also works
141
- directly — it's verified once at the start, so it finishes even if it runs past the visa TTL; only
142
- *multi-call* sessions need the sidecar's refresh. Raise `VISA_TTL_SECONDS` (300–900) to widen the
143
- window, but the sidecar is the real answer for long sessions.
144
-
145
- > If a client defaults to OpenAI `/responses` (some Continue configs for o-series/gpt-5), force
146
- > `/chat/completions` — PassControl intentionally proxies only chat/messages and model-listing
147
- > endpoints.
148
-
149
- ## CLI command center
150
-
151
- The primary interface is `passcontrol <command>`. Highlights:
152
-
153
- | Need | Command |
154
- |---|---|
155
- | Config, gateway status, suggested next steps | `passcontrol status` |
156
- | Check local setup / mint a test visa | `passcontrol doctor --deep` |
157
- | Make a governed model call | `passcontrol call "Summarize this"` |
158
- | Run the auto-refreshing bridge for an agent | `passcontrol sidecar` |
159
- | Print agent settings (OpenHands, Aider, Cline, Continue, LiteLLM) | `passcontrol env openhands` |
160
- | List / create agents | `passcontrol agent list` · `passcontrol agent create billing-bot` |
161
- | Suspend, resume, or revoke an agent | `passcontrol agent suspend <id>` |
162
- | Inspect spend, logs, and audit history | `passcontrol spend` · `passcontrol logs` · `passcontrol audit` |
163
- | Arm / release the tenant kill switch | `passcontrol kill on` · `passcontrol kill off` |
164
- | Prepare or repair local services | `passcontrol setup` · `passcontrol doctor --fix` |
165
- | Manage the local dashboard | `passcontrol start` · `passcontrol stop` · `passcontrol restart` |
166
- | Follow local dashboard logs | `passcontrol local-logs --follow` |
167
- | Open the Control Tower | `passcontrol open` |
168
- | Preview/write an agent config | `passcontrol configure aider` · `passcontrol configure aider --write` |
169
-
170
- Config resolves in order: **environment variables → project-local `.passcontrol` →
171
- `~/.config/passcontrol/config`**. `.passcontrol` holds a passport secret, is gitignored, and is
172
- written owner-only — never commit or share it.
173
-
174
- `passcontrol reset --local --confirm RESET` destroys and recreates local data — use it only for a
175
- clean slate.
176
-
177
- ## Using it from your own code
178
-
179
- The client SDK (vendored in [`./sdk`](./sdk)) hides the visa dance — point your provider SDK at the
180
- gateway and visas auto-refresh:
108
+ ## Using it from an agent
109
+ The client SDK hides the visa dance — point your provider SDK at the gateway:
181
110
 
182
111
  ```ts
183
112
  import OpenAI from "openai";
@@ -187,7 +116,10 @@ const pc = new PassControl({ gateway, passportId, passportSecret });
187
116
  const openai = new OpenAI(pc.clientOptions("openai")); // baseURL + auth wired; visas auto-refresh
188
117
  ```
189
118
 
190
- Manage the fleet programmatically with the control-plane SDK + an API key:
119
+ The SDK is vendored in this repo under `./sdk`; it is not a separately published npm package
120
+ yet.
121
+
122
+ Manage the fleet programmatically with the control-plane SDK + API key:
191
123
 
192
124
  ```ts
193
125
  import { ControlClient } from "./sdk";
@@ -196,92 +128,55 @@ await cp.agents.list();
196
128
  await cp.killSwitch.set(true);
197
129
  ```
198
130
 
199
- The SDK is not a separately published npm package yet. Full API reference:
200
- [`openapi.yaml`](./openapi.yaml) and [`DOCUMENTATION.md`](./DOCUMENTATION.md). Runnable example
201
- agents live in [`examples/`](./examples).
202
-
203
- ## Self-host
204
-
205
- Stack: **Next.js** (App Router, edge routes) · **Supabase** (Postgres + Vault + Auth) · **Upstash /
206
- any Redis**. Deploy on Vercel or any Node host (`next start`). No Vercel-proprietary services are
207
- required — the kill switch is Redis-backed.
131
+ Full API reference: [`openapi.yaml`](./openapi.yaml) and [`DOCUMENTATION.md`](./DOCUMENTATION.md).
132
+ Runnable example agents in [`examples/`](./examples).
208
133
 
209
- ### Local (Docker) — the fastest path
134
+ ## Use it from Claude Desktop, Cursor, or Claude Code (MCP)
135
+ `passcontrol mcp` runs a local [MCP](https://modelcontextprotocol.io) server that exposes two
136
+ tools — `chat` and `list_models` — to any MCP client. Every `chat` goes through the gateway,
137
+ so the provider key stays server-side and the passport's scope, budget, and kill switch all
138
+ apply. The client sees the model's response, never your key.
210
139
 
211
- `passcontrol setup` (above) is the one-command route. Under the hood it runs the bundled Docker
212
- stack: local Supabase (Postgres + Vault + Auth), Redis-over-REST, migrations applied inside the DB
213
- container, and a seeded dev user. Prereqs: **Docker Desktop, the Supabase CLI, Node 18+** — no host
214
- `psql` required.
215
-
216
- From a source checkout you can drive the same thing directly:
140
+ Set it up once. Your passport lives in a single trusted local file; the client config never
141
+ holds a secret:
217
142
 
218
143
  ```bash
219
- git clone https://github.com/Vertias3u/PassControl && cd PassControl
220
- npm install
221
- npm run cli -- setup # or: passcontrol setup after `npm link`
144
+ passcontrol init --global # store the passport once (~/.config/passcontrol)
145
+ passcontrol configure claude-desktop --write # merge a secret-free MCP entry into the client
146
+ # then restart Claude Desktop
222
147
  ```
223
148
 
224
- ### Manual self-host
225
-
226
- > **Supabase specifically** (not vanilla Postgres): the credential vault uses the `supabase_vault`
227
- > extension, so you need a Supabase project — hosted or the self-hosted Supabase stack — not a
228
- > plain Postgres database.
229
-
230
- ```bash
231
- git clone https://github.com/Vertias3u/PassControl && cd PassControl
232
- npm install
233
- cp .env.example .env.local # fill in Supabase / Redis / secrets
234
- DATABASE_URL='postgresql://…' npm run migrate # applies db/migrations/*.sql in order, once each
235
- npm run dev # or build + `next start` on any Node host
236
- ```
237
-
238
- See [`.env.example`](./.env.example) for the full config (Supabase URL/keys, `VISA_SECRET`,
239
- `CACHE_ENC_KEY`, Redis, `CRON_SECRET`, `INVITE_CODE`). Apply migrations `0001 → …` in order;
240
- [`db/tests/rls_invariants.sql`](./db/tests/rls_invariants.sql) checks tenant isolation and the
241
- privileged-column locks on your database.
242
-
243
- **Background reconcile job (required on non-Vercel hosts):** a periodic `GET /api/cron/reconcile`
244
- (header `Authorization: Bearer $CRON_SECRET`) corrects budget drift and flushes last-seen. On
245
- Vercel it's wired via `vercel.json`; elsewhere schedule it yourself (system `cron`, a GitHub
246
- Action…) every few minutes. It's a correction layer, not the hot path — an occasional missed run is
247
- harmless.
248
-
249
- ## Providers & endpoints
250
-
251
- Supported providers: **OpenAI, Anthropic, Groq, Mistral, Together, DeepSeek**. The gateway proxies
252
- **only chat and model-listing endpoints** — OpenAI-shaped chat completions + models, Anthropic
253
- messages + models, DeepSeek chat completions. It does **not** proxy embeddings, files, fine-tuning,
254
- batches, `/responses`, or token-counting endpoints (that's the point — a leaked visa can't reach
255
- your full provider surface).
149
+ Swap `claude-desktop` for `cursor`, or for Claude Code run the printed
150
+ `claude mcp add --scope user passcontrol -- passcontrol mcp`. Ask the client to use the `chat`
151
+ tool and the call is governed end-to-end — arm the kill switch and the next tool call is
152
+ refused. Run `passcontrol env claude-desktop` to preview the config without writing it.
256
153
 
257
154
  ## Limitations
258
-
259
- - A work-visa is a **bearer token**, reusable until it expires (≤5 min). Keep it out of logs and
260
- prompts; use suspend/kill to block future requests immediately.
261
- - **Pricing** is a best-effort in-code table and can lag provider price changes. Use it for budgets
262
- and monitoring, not billing reconciliation against provider invoices.
263
- - **Instant revocation** assumes Redis is configured for persistence / no-eviction. If Redis evicts
264
- suspend/kill keys, enforcement falls back to short visa TTLs and the durable agent-status check at
265
- the next mint.
155
+ - A work-visa is a bearer token and is reusable until it expires (≤5 minutes). Keep it out
156
+ of logs and prompts; use suspend/kill switches to block future requests.
157
+ - The gateway proxies only chat and model-listing endpoints: OpenAI/Groq/Mistral/Together
158
+ chat completions and models, Anthropic messages and models, and DeepSeek chat
159
+ completions. It does **not** proxy embeddings, files, fine-tuning, batches, responses, or
160
+ token-counting endpoints.
161
+ - Pricing is a best-effort in-code table and can lag provider price changes. Use it for
162
+ budgets and monitoring, not as billing reconciliation against provider invoices.
163
+ - Instant revocation assumes Redis is configured for persistence/no-eviction behavior. If
164
+ Redis evicts suspend/kill keys, enforcement falls back to short visa TTLs and durable agent
165
+ status checks at the next mint.
266
166
 
267
167
  ## Security
268
-
269
- Security is the whole point, so please report issues privately rather than opening a public issue:
270
- **security@vertias.eu**. We'll acknowledge and work with you on a fix + disclosure timeline.
271
-
272
- - It's **BYOK** — your provider key lives encrypted in your own Supabase Vault, decrypted only
273
- in-flight and cached briefly (encrypted) in your own Redis. It is never logged or returned.
274
- - Tenant isolation is enforced by Postgres **RLS on every table**; the sole decrypt path is a
275
- `SECURITY DEFINER`, service-role-only function.
168
+ Security is the point of this project, so please report issues privately rather than opening
169
+ a public issue: **security@vertias.eu**. We'll acknowledge and work with you on a fix +
170
+ disclosure timeline. Notes:
171
+ - It's **BYOK** — your provider key lives encrypted in your own Supabase Vault; it's
172
+ decrypted only in-flight and cached briefly (encrypted) in your own Redis.
276
173
  - It is **not yet independently audited.** If you find a hole, you're doing us a favor.
277
174
 
278
175
  ## License
279
-
280
176
  Source-available under the **Business Source License (BSL 1.1)** — read it, run it, modify it,
281
177
  self-host it. The one restriction: you may not offer it as a competing hosted/managed service.
282
178
  Converts to Apache 2.0 after the change date. See [`LICENSE`](./LICENSE).
283
179
 
284
180
  ## Contributing
285
-
286
181
  Issues and PRs welcome. Run `npm run typecheck && npm test && npm run build` before a PR (CI
287
- enforces it). Be kind — this is early.
182
+ enforces it). Be kind; this is early.
@@ -11,6 +11,7 @@ import {
11
11
  CONFIG_FILE,
12
12
  OPENAI_SHAPE_PROVIDERS,
13
13
  PROVIDERS,
14
+ assertConfigLoaded,
14
15
  config,
15
16
  configPathLabel,
16
17
  defaultModelForProvider,
@@ -25,12 +26,28 @@ import {
25
26
  step,
26
27
  writeConfigFile,
27
28
  } from "../cli/config.mjs";
29
+ import {
30
+ CLAUDE_CODE_ADD_COMMAND,
31
+ isMcpIntegration,
32
+ mcpClientConfigPath,
33
+ mcpServerEntry,
34
+ mcpServersDocument,
35
+ writeMcpClientConfig,
36
+ } from "../cli/mcp/integration.mjs";
28
37
  import { startSidecar } from "../cli/sidecar.mjs";
29
38
 
30
39
  const b64url = (bytes) =>
31
40
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
32
41
  const fromB64url = (s) => new Uint8Array(Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64"));
33
- const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
42
+ const CLI_ENTRY = fileURLToPath(import.meta.url);
43
+ const PACKAGE_ROOT = path.resolve(path.dirname(CLI_ENTRY), "..");
44
+ const CLI_VERSION = (() => {
45
+ try {
46
+ return JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, "package.json"), "utf8")).version ?? "0.0.0";
47
+ } catch {
48
+ return "0.0.0";
49
+ }
50
+ })();
34
51
  const DASHBOARD_STATE_FILE = "local-dashboard.json";
35
52
  const APP_STATE_FILE = "app.json";
36
53
  const PUBLIC_REPO_URL = "https://github.com/Vertias3u/PassControl.git";
@@ -99,8 +116,11 @@ Usage:
99
116
  clone the app (if needed), start local services, open the dashboard
100
117
  ${cmd} call "hi" mint a visa and call a model
101
118
  ${cmd} sidecar [--port 8788] start the local agent bridge
119
+ ${cmd} mcp start the local stdio MCP server
102
120
  ${cmd} env [openhands] print sidecar settings for agents
103
- ${cmd} configure <integration> [--write]
121
+ ${cmd} env claude-desktop|cursor|claude-code
122
+ print secret-free MCP client settings
123
+ ${cmd} configure <integration> [--write] [--force]
104
124
  preview or create a supported integration config
105
125
  ${cmd} agent list list agents
106
126
  ${cmd} agent create <name> create an agent passport
@@ -974,17 +994,25 @@ async function logsCommand(opts) {
974
994
  })
975
995
  );
976
996
  console.table(
977
- rows.map((row) => ({
978
- at: row.created_at,
979
- agent: row.agent_id,
980
- provider: row.provider,
981
- model: row.model,
982
- status: row.status,
983
- in: row.input_tokens,
984
- out: row.output_tokens,
985
- total: row.total_tokens,
986
- usd: usd(row.cost_microcents),
987
- }))
997
+ rows.map((row) => {
998
+ const input = typeof row.input_tokens === "number" && Number.isFinite(row.input_tokens)
999
+ ? row.input_tokens
1000
+ : null;
1001
+ const output = typeof row.output_tokens === "number" && Number.isFinite(row.output_tokens)
1002
+ ? row.output_tokens
1003
+ : null;
1004
+ return {
1005
+ at: row.created_at,
1006
+ agent: row.agent_id,
1007
+ provider: row.provider,
1008
+ model: row.model,
1009
+ status: row.status,
1010
+ in: input ?? "-",
1011
+ out: output ?? "-",
1012
+ total: input === null && output === null ? "-" : (input ?? 0) + (output ?? 0),
1013
+ usd: usd(row.cost_microcents),
1014
+ };
1015
+ })
988
1016
  );
989
1017
  }
990
1018
 
@@ -1018,6 +1046,12 @@ async function sidecarCommand(rest, opts) {
1018
1046
  }
1019
1047
  }
1020
1048
 
1049
+ async function mcpCommand() {
1050
+ const { passportId, passportSecret } = requirePassport(config);
1051
+ const { startMcpServer } = await import("../cli/mcp/server.mjs");
1052
+ await startMcpServer({ gateway: config.gateway, passportId, passportSecret });
1053
+ }
1054
+
1021
1055
  function sidecarBaseUrl(opts = {}) {
1022
1056
  const provider = String(opts.provider || config.provider);
1023
1057
  assertProvider(provider);
@@ -1041,8 +1075,42 @@ function printExports(values) {
1041
1075
  }
1042
1076
  }
1043
1077
 
1078
+ function requireGlobalMcpPassport() {
1079
+ assertConfigLoaded();
1080
+ const globalSource = config.sources.find((source) => source.type === "global");
1081
+ const passportId = String(globalSource?.values?.PASSPORT_ID ?? "").trim();
1082
+ const passportSecret = String(globalSource?.values?.PASSPORT_SECRET ?? "").trim();
1083
+ if (!passportId || !passportSecret) {
1084
+ throw new Error(
1085
+ "MCP client setup requires a passport in the global PassControl config. Run `passcontrol init --global` first."
1086
+ );
1087
+ }
1088
+ }
1089
+
1090
+ function passControlMcpEntry() {
1091
+ return mcpServerEntry({ cliPath: CLI_ENTRY });
1092
+ }
1093
+
1094
+ function printMcpPreset(integration) {
1095
+ requireGlobalMcpPassport();
1096
+ if (integration === "claude-code") {
1097
+ console.log("# Add PassControl to Claude Code:");
1098
+ console.log(CLAUDE_CODE_ADD_COMMAND);
1099
+ return;
1100
+ }
1101
+
1102
+ const label = integration === "cursor" ? "Cursor" : "Claude Desktop";
1103
+ console.log(`# ${label} mcpServers config:`);
1104
+ console.log(JSON.stringify(mcpServersDocument(passControlMcpEntry()), null, 2));
1105
+ }
1106
+
1044
1107
  function printAgentPreset(name = "generic", opts = {}) {
1045
1108
  const preset = name.toLowerCase();
1109
+ if (isMcpIntegration(preset)) {
1110
+ printMcpPreset(preset);
1111
+ return;
1112
+ }
1113
+
1046
1114
  const { provider, model, apiKey, baseUrl } = sidecarBaseUrl(opts);
1047
1115
  const modelWithProvider = `${provider}/${model}`;
1048
1116
  const sidecarStart = opts.port ? cliCommand(`sidecar --port ${opts.port}`) : cliCommand("sidecar");
@@ -1089,7 +1157,9 @@ function printAgentPreset(name = "generic", opts = {}) {
1089
1157
  ]);
1090
1158
  break;
1091
1159
  default:
1092
- throw new Error("Usage: passcontrol env [generic|openhands|litellm|aider|cline|continue]");
1160
+ throw new Error(
1161
+ "Usage: passcontrol env [generic|openhands|litellm|aider|cline|continue|claude-desktop|cursor|claude-code]"
1162
+ );
1093
1163
  }
1094
1164
  }
1095
1165
 
@@ -1105,9 +1175,43 @@ function aiderConfig(opts = {}) {
1105
1175
  ].join("\n");
1106
1176
  }
1107
1177
 
1178
+ function configureMcpClient(integration, opts = {}) {
1179
+ requireGlobalMcpPassport();
1180
+ if (integration === "claude-code") {
1181
+ console.log("Claude Code manages MCP servers through its CLI. Run:");
1182
+ console.log(CLAUDE_CODE_ADD_COMMAND);
1183
+ return;
1184
+ }
1185
+
1186
+ const target = mcpClientConfigPath(integration);
1187
+ const entry = passControlMcpEntry();
1188
+ const preview = JSON.stringify(mcpServersDocument(entry), null, 2);
1189
+ console.log(`Preview: ${target}\n\n${preview}`);
1190
+ if (!opts.write) {
1191
+ step("Dry run only. Re-run with `--write` to merge this entry.");
1192
+ return;
1193
+ }
1194
+
1195
+ const result = writeMcpClientConfig({ target, entry, force: Boolean(opts.force) });
1196
+ if (!result.changed) {
1197
+ ok(`${target} already contains this PassControl MCP entry`);
1198
+ return;
1199
+ }
1200
+ if (result.backupPath) step(`backed up ${result.backupPath}`);
1201
+ ok(`wrote ${target}`);
1202
+ }
1203
+
1108
1204
  async function configureCommand(rest, opts = {}) {
1109
1205
  const integration = String(rest[0] ?? "").toLowerCase();
1110
- if (!integration) throw new Error("Usage: passcontrol configure <aider|cline|continue|openhands> [--write]");
1206
+ if (!integration) {
1207
+ throw new Error(
1208
+ "Usage: passcontrol configure <aider|cline|continue|openhands|claude-desktop|cursor|claude-code> [--write] [--force]"
1209
+ );
1210
+ }
1211
+ if (isMcpIntegration(integration)) {
1212
+ configureMcpClient(integration, opts);
1213
+ return;
1214
+ }
1111
1215
  if (integration !== "aider") {
1112
1216
  if (opts.write) throw new Error(`${integration} configuration is UI- or project-schema-specific; no file was written. Use the preview below.`);
1113
1217
  printAgentPreset(integration, opts);
@@ -1217,7 +1321,7 @@ async function main() {
1217
1321
  return;
1218
1322
  }
1219
1323
  if (opts.version || command === "version") {
1220
- console.log("passcontrol 0.1.0");
1324
+ console.log(`passcontrol ${CLI_VERSION}`);
1221
1325
  return;
1222
1326
  }
1223
1327
 
@@ -1256,6 +1360,9 @@ async function main() {
1256
1360
  case "sidecar":
1257
1361
  await sidecarCommand(commandRest, opts);
1258
1362
  break;
1363
+ case "mcp":
1364
+ await mcpCommand();
1365
+ break;
1259
1366
  case "env":
1260
1367
  printAgentPreset(commandRest[0] || "generic", opts);
1261
1368
  break;
@@ -0,0 +1,54 @@
1
+ # PassControl MCP server
2
+
3
+ `passcontrol mcp` starts a local stdio MCP server with `chat` and `list_models`.
4
+ It reads the same environment, nearest `.passcontrol`, and global
5
+ `~/.config/passcontrol/config` sources as the rest of the CLI. MCP client setup requires a
6
+ passport in the global profile so clients can launch from any working directory without
7
+ embedding a secret:
8
+
9
+ ```sh
10
+ passcontrol init --global
11
+ ```
12
+
13
+ The client receives neither the provider key nor the short-lived work visa. The
14
+ server mints the visa locally and sends every model call through the configured
15
+ PassControl gateway.
16
+
17
+ ## Claude Desktop
18
+
19
+ Preview or merge the entry into Claude Desktop's real per-OS config path:
20
+
21
+ ```sh
22
+ passcontrol env claude-desktop
23
+ passcontrol configure claude-desktop --write
24
+ ```
25
+
26
+ ## Cursor
27
+
28
+ Preview or merge `mcpServers.passcontrol` into `~/.cursor/mcp.json`:
29
+
30
+ ```sh
31
+ passcontrol env cursor
32
+ passcontrol configure cursor --write
33
+ ```
34
+
35
+ ## Claude Code
36
+
37
+ Claude Code manages this setting through its CLI. Either command below prints the exact
38
+ `claude mcp add` command to run:
39
+
40
+ ```sh
41
+ passcontrol env claude-code
42
+ passcontrol configure claude-code
43
+ ```
44
+
45
+ The equivalent private, user-scoped command is:
46
+
47
+ ```sh
48
+ claude mcp add --scope user passcontrol -- passcontrol mcp
49
+ ```
50
+
51
+ Desktop/Cursor entries use absolute Node and `bin/passcontrol.mjs` paths because GUI clients
52
+ may not inherit shell `PATH`. Existing `mcpServers` entries are preserved, an existing file is
53
+ backed up to `.bak`, and a different PassControl entry requires `--force`. No generated client
54
+ config contains a passport secret or provider key.
@@ -0,0 +1,158 @@
1
+ import { decodeJwt } from "jose";
2
+ import { OPENAI_SHAPE_PROVIDERS, formatProxyError } from "../config.mjs";
3
+ import { createVisaClient } from "../visa-client.mjs";
4
+
5
+ const DEFAULT_ANTHROPIC_MAX_TOKENS = 1024;
6
+
7
+ const trimSlash = (value) => String(value ?? "").replace(/\/+$/, "");
8
+
9
+ function requestFor({ provider, model, messages, max_tokens, temperature }) {
10
+ if (provider === "anthropic") {
11
+ const system = messages
12
+ .filter((message) => message.role === "system")
13
+ .map((message) => message.content)
14
+ .join("\n\n");
15
+ const providerMessages = messages.filter((message) => message.role !== "system");
16
+ if (providerMessages.length === 0) {
17
+ throw new Error("Anthropic chat requires at least one user or assistant message.");
18
+ }
19
+
20
+ return {
21
+ path: "v1/messages",
22
+ body: {
23
+ model,
24
+ max_tokens: max_tokens ?? DEFAULT_ANTHROPIC_MAX_TOKENS,
25
+ messages: providerMessages,
26
+ ...(system ? { system } : {}),
27
+ ...(temperature === undefined ? {} : { temperature }),
28
+ },
29
+ };
30
+ }
31
+
32
+ if (OPENAI_SHAPE_PROVIDERS.has(provider)) {
33
+ return {
34
+ path: "chat/completions",
35
+ body: {
36
+ model,
37
+ messages,
38
+ ...(max_tokens === undefined ? {} : { max_tokens }),
39
+ ...(temperature === undefined ? {} : { temperature }),
40
+ },
41
+ };
42
+ }
43
+
44
+ throw new Error(`Provider ${provider} is not supported by PassControl MCP.`);
45
+ }
46
+
47
+ function extractAssistantText(provider, data) {
48
+ if (provider === "anthropic") {
49
+ const text = Array.isArray(data?.content)
50
+ ? data.content
51
+ .filter((part) => part?.type === "text" && typeof part.text === "string")
52
+ .map((part) => part.text)
53
+ .join("")
54
+ : "";
55
+ if (text) return text;
56
+ } else {
57
+ const content = data?.choices?.[0]?.message?.content;
58
+ if (typeof content === "string" && content) return content;
59
+ if (Array.isArray(content)) {
60
+ const text = content
61
+ .map((part) => (typeof part === "string" ? part : typeof part?.text === "string" ? part.text : ""))
62
+ .join("");
63
+ if (text) return text;
64
+ }
65
+ }
66
+
67
+ throw new Error(`${provider} returned no assistant text.`);
68
+ }
69
+
70
+ function proxyError(status, body) {
71
+ if (status === 401) {
72
+ const detail = String(body ?? "").trim();
73
+ return `Gateway rejected the work visa with 401: ${detail}. Check the passport and gateway, then retry.`;
74
+ }
75
+ return formatProxyError(status, body);
76
+ }
77
+
78
+ function usageFrom(data) {
79
+ return data?.usage && typeof data.usage === "object" && !Array.isArray(data.usage)
80
+ ? data.usage
81
+ : undefined;
82
+ }
83
+
84
+ function modelsFromVisa(visa) {
85
+ let payload;
86
+ try {
87
+ payload = decodeJwt(visa);
88
+ } catch {
89
+ throw new Error("Gateway returned a work visa with an unreadable scope.");
90
+ }
91
+
92
+ if (!Array.isArray(payload.scope)) {
93
+ throw new Error("Gateway work visa did not contain a model scope.");
94
+ }
95
+
96
+ return payload.scope.flatMap((entry) => {
97
+ if (!entry || typeof entry.provider !== "string" || !Array.isArray(entry.models)) return [];
98
+ return entry.models
99
+ .filter((model) => typeof model === "string")
100
+ .map((model) => ({ provider: entry.provider, model }));
101
+ });
102
+ }
103
+
104
+ export function createGatewayClient({
105
+ gateway,
106
+ passportId,
107
+ passportSecret,
108
+ fetch: fetchImpl = globalThis.fetch,
109
+ now = () => Date.now(),
110
+ randomUUID = () => globalThis.crypto.randomUUID(),
111
+ refreshSkewSeconds = 30,
112
+ }) {
113
+ const baseUrl = trimSlash(gateway);
114
+ const visas = createVisaClient({
115
+ gateway: baseUrl,
116
+ passportId,
117
+ passportSecret,
118
+ fetch: fetchImpl,
119
+ now,
120
+ randomUUID,
121
+ refreshSkewSeconds,
122
+ missingVisaMessage: "Challenge returned no visa.",
123
+ });
124
+
125
+ async function proxyChat(input, visa) {
126
+ const { path, body } = requestFor(input);
127
+ return fetchImpl(`${baseUrl}/api/v1/${input.provider}/${path}`, {
128
+ method: "POST",
129
+ headers: {
130
+ "content-type": "application/json",
131
+ authorization: `Bearer ${visa}`,
132
+ },
133
+ body: JSON.stringify(body),
134
+ });
135
+ }
136
+
137
+ return {
138
+ async chat(input) {
139
+ const response = await visas.fetchWithVisa((visa) => proxyChat(input, visa));
140
+ if (!response.ok) throw new Error(proxyError(response.status, await response.text()));
141
+
142
+ let data;
143
+ try {
144
+ data = await response.json();
145
+ } catch {
146
+ throw new Error(`Gateway returned a non-JSON ${input.provider} response.`);
147
+ }
148
+ return {
149
+ text: extractAssistantText(input.provider, data),
150
+ usage: usageFrom(data),
151
+ };
152
+ },
153
+
154
+ async listModels() {
155
+ return modelsFromVisa(await visas.getVisa());
156
+ },
157
+ };
158
+ }
@@ -0,0 +1,96 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { isDeepStrictEqual } from "node:util";
5
+
6
+ export const MCP_INTEGRATIONS = new Set(["claude-desktop", "cursor", "claude-code"]);
7
+ export const CLAUDE_CODE_ADD_COMMAND =
8
+ "claude mcp add --scope user passcontrol -- passcontrol mcp";
9
+
10
+ export function isMcpIntegration(name) {
11
+ return MCP_INTEGRATIONS.has(name);
12
+ }
13
+
14
+ export function mcpServerEntry({ cliPath, nodePath = process.execPath }) {
15
+ return {
16
+ command: path.resolve(nodePath),
17
+ args: [path.resolve(cliPath), "mcp"],
18
+ };
19
+ }
20
+
21
+ export function mcpServersDocument(entry) {
22
+ return { mcpServers: { passcontrol: entry } };
23
+ }
24
+
25
+ export function mcpClientConfigPath(
26
+ integration,
27
+ { platform = process.platform, home = os.homedir(), env = process.env } = {}
28
+ ) {
29
+ if (integration === "cursor") return path.join(home, ".cursor", "mcp.json");
30
+ if (integration !== "claude-desktop") return null;
31
+
32
+ if (platform === "darwin") {
33
+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");
34
+ }
35
+ if (platform === "win32") {
36
+ const appData = env.APPDATA || path.join(home, "AppData", "Roaming");
37
+ return path.join(appData, "Claude", "claude_desktop_config.json");
38
+ }
39
+ const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
40
+ return path.join(configHome, "Claude", "claude_desktop_config.json");
41
+ }
42
+
43
+ function readConfigObject(target) {
44
+ if (!fs.existsSync(target)) return { exists: false, value: {} };
45
+
46
+ let value;
47
+ try {
48
+ value = JSON.parse(fs.readFileSync(target, "utf8"));
49
+ } catch (error) {
50
+ throw new Error(`Cannot parse ${target}: ${error.message}`);
51
+ }
52
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
53
+ throw new Error(`${target} must contain a JSON object.`);
54
+ }
55
+ if (
56
+ value.mcpServers !== undefined &&
57
+ (!value.mcpServers || typeof value.mcpServers !== "object" || Array.isArray(value.mcpServers))
58
+ ) {
59
+ throw new Error(`${target} has an invalid mcpServers value; expected a JSON object.`);
60
+ }
61
+ return { exists: true, value };
62
+ }
63
+
64
+ export function writeMcpClientConfig({ target, entry, force = false }) {
65
+ const { exists, value } = readConfigObject(target);
66
+ const mcpServers = value.mcpServers ?? {};
67
+ const hasPassControl = Object.prototype.hasOwnProperty.call(mcpServers, "passcontrol");
68
+ if (hasPassControl && !isDeepStrictEqual(mcpServers.passcontrol, entry) && !force) {
69
+ throw new Error(
70
+ `${target} already has a different mcpServers.passcontrol entry; re-run with --force to replace only that entry.`
71
+ );
72
+ }
73
+ if (hasPassControl && isDeepStrictEqual(mcpServers.passcontrol, entry)) {
74
+ return { changed: false, backupPath: null };
75
+ }
76
+
77
+ const merged = {
78
+ ...value,
79
+ mcpServers: {
80
+ ...mcpServers,
81
+ passcontrol: entry,
82
+ },
83
+ };
84
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
85
+
86
+ let backupPath = null;
87
+ if (exists) {
88
+ backupPath = `${target}.bak`;
89
+ fs.copyFileSync(target, backupPath);
90
+ fs.chmodSync(backupPath, 0o600);
91
+ }
92
+
93
+ fs.writeFileSync(target, `${JSON.stringify(merged, null, 2)}\n`, { mode: 0o600 });
94
+ fs.chmodSync(target, 0o600);
95
+ return { changed: true, backupPath };
96
+ }
@@ -0,0 +1,114 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod/v4";
4
+ import { PROVIDERS } from "../config.mjs";
5
+ import { createGatewayClient } from "./gateway.mjs";
6
+
7
+ const messageSchema = z.object({
8
+ role: z.enum(["system", "user", "assistant"]),
9
+ content: z.string().min(1),
10
+ });
11
+
12
+ const usageSchema = z.record(z.string(), z.unknown());
13
+ const modelSchema = z.object({
14
+ provider: z.string(),
15
+ model: z.string(),
16
+ });
17
+
18
+ function toolError(error) {
19
+ return {
20
+ content: [
21
+ {
22
+ type: "text",
23
+ text: error instanceof Error ? error.message : String(error),
24
+ },
25
+ ],
26
+ isError: true,
27
+ };
28
+ }
29
+
30
+ export function createMcpServer(options) {
31
+ const gateway = createGatewayClient(options);
32
+ const server = new McpServer(
33
+ { name: "passcontrol", version: "0.2.0" },
34
+ {
35
+ instructions:
36
+ "Use chat for governed model calls through PassControl. Every chat call is subject to the configured passport's scope, budget, and kill switches.",
37
+ }
38
+ );
39
+
40
+ server.registerTool(
41
+ "chat",
42
+ {
43
+ title: "Governed model chat",
44
+ description:
45
+ "Call a supported model through the PassControl gateway. The provider key stays in the gateway; passport scope, budget, and kill switches apply.",
46
+ inputSchema: {
47
+ provider: z.enum(PROVIDERS),
48
+ model: z.string().min(1),
49
+ messages: z.array(messageSchema).min(1),
50
+ max_tokens: z.number().int().positive().optional(),
51
+ temperature: z.number().min(0).max(2).optional(),
52
+ },
53
+ outputSchema: {
54
+ text: z.string(),
55
+ usage: usageSchema.optional(),
56
+ },
57
+ annotations: {
58
+ destructiveHint: false,
59
+ idempotentHint: false,
60
+ openWorldHint: true,
61
+ },
62
+ },
63
+ async (input) => {
64
+ try {
65
+ const result = await gateway.chat(input);
66
+ const structuredContent = {
67
+ text: result.text,
68
+ ...(result.usage ? { usage: result.usage } : {}),
69
+ };
70
+ return {
71
+ content: [{ type: "text", text: result.text }],
72
+ structuredContent,
73
+ };
74
+ } catch (error) {
75
+ return toolError(error);
76
+ }
77
+ }
78
+ );
79
+
80
+ server.registerTool(
81
+ "list_models",
82
+ {
83
+ title: "List scoped models",
84
+ description:
85
+ "List provider/model patterns in the gateway-issued scope for the configured passport.",
86
+ outputSchema: { models: z.array(modelSchema) },
87
+ annotations: {
88
+ readOnlyHint: true,
89
+ destructiveHint: false,
90
+ idempotentHint: true,
91
+ openWorldHint: false,
92
+ },
93
+ },
94
+ async () => {
95
+ try {
96
+ const structuredContent = { models: await gateway.listModels() };
97
+ return {
98
+ content: [{ type: "text", text: JSON.stringify(structuredContent, null, 2) }],
99
+ structuredContent,
100
+ };
101
+ } catch (error) {
102
+ return toolError(error);
103
+ }
104
+ }
105
+ );
106
+
107
+ return server;
108
+ }
109
+
110
+ export async function startMcpServer(options) {
111
+ const server = createMcpServer(options);
112
+ await server.connect(new StdioServerTransport());
113
+ return server;
114
+ }
package/cli/sidecar.mjs CHANGED
@@ -1,48 +1,19 @@
1
1
  import http from "node:http";
2
2
  import { Readable } from "node:stream";
3
- import { ed25519 } from "@noble/curves/ed25519";
4
- import { fail, formatChallengeError, ok, step } from "./config.mjs";
5
-
6
- const b64url = (bytes) =>
7
- Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
8
- const fromB64url = (s) => new Uint8Array(Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64"));
3
+ import { fail, ok, step } from "./config.mjs";
4
+ import { createVisaClient } from "./visa-client.mjs";
9
5
 
10
6
  const STRIP_REQ = new Set(["authorization", "x-api-key", "host", "content-length", "accept-encoding", "connection"]);
11
7
  const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
12
8
 
13
9
  export function createSidecar({ gateway, passportId, passportSecret, port = 8788, host = "127.0.0.1", refreshSkewSeconds = 30 }) {
14
- const skewMs = Math.max(0, Number(refreshSkewSeconds) * 1000);
15
- let cached = null;
16
- let inflight = null;
17
-
18
- async function mint() {
19
- const obj = { passport_id: passportId, ts: Date.now(), nonce: crypto.randomUUID() };
20
- const payload = b64url(new TextEncoder().encode(JSON.stringify(obj)));
21
- const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
22
- const res = await fetch(`${gateway}/api/auth/challenge`, {
23
- method: "POST",
24
- headers: { "content-type": "application/json" },
25
- body: JSON.stringify({ payload, signature }),
26
- });
27
- if (!res.ok) throw new Error(formatChallengeError(res.status, await res.text()));
28
- const { visa, expires_in } = await res.json();
29
- if (!visa) throw new Error("challenge returned no visa");
30
- return { token: visa, expiresAt: Date.now() + (expires_in ?? 300) * 1000 };
31
- }
32
-
33
- async function getVisa() {
34
- if (cached && Date.now() < cached.expiresAt - skewMs) return cached.token;
35
- if (inflight) return inflight;
36
- inflight = mint()
37
- .then((v) => {
38
- cached = v;
39
- return v.token;
40
- })
41
- .finally(() => {
42
- inflight = null;
43
- });
44
- return inflight;
45
- }
10
+ const visas = createVisaClient({
11
+ gateway,
12
+ passportId,
13
+ passportSecret,
14
+ refreshSkewSeconds,
15
+ missingVisaMessage: "challenge returned no visa",
16
+ });
46
17
 
47
18
  function readBody(req) {
48
19
  return new Promise((resolve, reject) => {
@@ -76,11 +47,7 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
76
47
  const server = http.createServer(async (req, res) => {
77
48
  try {
78
49
  const body = await readBody(req);
79
- let upstream = await fetchUpstream(req, body, await getVisa());
80
- if (upstream.status === 401) {
81
- cached = null;
82
- upstream = await fetchUpstream(req, body, await getVisa());
83
- }
50
+ const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, body, visa));
84
51
  writeResponse(res, upstream);
85
52
  } catch (e) {
86
53
  if (!res.headersSent) {
@@ -92,7 +59,7 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
92
59
  }
93
60
  });
94
61
 
95
- return { server, getVisa };
62
+ return { server, getVisa: visas.getVisa };
96
63
  }
97
64
 
98
65
  export function startSidecar(opts) {
@@ -0,0 +1,74 @@
1
+ import { ed25519 } from "@noble/curves/ed25519";
2
+ import { formatChallengeError } from "./config.mjs";
3
+
4
+ const b64url = (bytes) =>
5
+ Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
6
+ const fromB64url = (value) =>
7
+ new Uint8Array(Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/"), "base64"));
8
+
9
+ export function createVisaClient({
10
+ gateway,
11
+ passportId,
12
+ passportSecret,
13
+ fetch: fetchImpl = (...args) => globalThis.fetch(...args),
14
+ now = () => Date.now(),
15
+ randomUUID = () => globalThis.crypto.randomUUID(),
16
+ refreshSkewSeconds = 30,
17
+ missingVisaMessage = "Challenge returned no visa.",
18
+ }) {
19
+ const skewMs = Math.max(0, Number(refreshSkewSeconds) * 1000);
20
+ let cached = null;
21
+ let inflight = null;
22
+
23
+ async function mint() {
24
+ const payloadObject = { passport_id: passportId, ts: now(), nonce: randomUUID() };
25
+ const payload = b64url(new TextEncoder().encode(JSON.stringify(payloadObject)));
26
+ const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
27
+ const response = await fetchImpl(`${gateway}/api/auth/challenge`, {
28
+ method: "POST",
29
+ headers: { "content-type": "application/json" },
30
+ body: JSON.stringify({ payload, signature }),
31
+ });
32
+
33
+ if (!response.ok) {
34
+ throw new Error(formatChallengeError(response.status, await response.text()));
35
+ }
36
+
37
+ const data = await response.json();
38
+ if (!data.visa) throw new Error(missingVisaMessage);
39
+ return {
40
+ token: data.visa,
41
+ expiresAt: now() + (data.expires_in ?? 300) * 1000,
42
+ };
43
+ }
44
+
45
+ async function getVisa() {
46
+ if (cached && now() < cached.expiresAt - skewMs) return cached.token;
47
+ if (inflight) return inflight;
48
+
49
+ inflight = mint()
50
+ .then((visa) => {
51
+ cached = visa;
52
+ return visa.token;
53
+ })
54
+ .finally(() => {
55
+ inflight = null;
56
+ });
57
+ return inflight;
58
+ }
59
+
60
+ function invalidate() {
61
+ cached = null;
62
+ }
63
+
64
+ async function fetchWithVisa(request) {
65
+ let response = await request(await getVisa());
66
+ if (response.status === 401) {
67
+ invalidate();
68
+ response = await request(await getVisa());
69
+ }
70
+ return response;
71
+ }
72
+
73
+ return { getVisa, invalidate, fetchWithVisa };
74
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Secure Agent Control Plane & Passport Vault — identity-aware reverse proxy for AI agent credentials.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://github.com/Vertias3u/PassControl#readme",
@@ -32,6 +32,7 @@
32
32
  "files": [
33
33
  "bin",
34
34
  "cli",
35
+ "!cli/**/__tests__",
35
36
  "LICENSE",
36
37
  "README.md"
37
38
  ],
@@ -57,6 +58,7 @@
57
58
  },
58
59
  "dependencies": {
59
60
  "@base-ui/react": "^1.5.0",
61
+ "@modelcontextprotocol/sdk": "^1.29.0",
60
62
  "@noble/curves": "^1.6.0",
61
63
  "@noble/hashes": "^1.5.0",
62
64
  "@sentry/nextjs": "^10.64.0",
@@ -73,7 +75,8 @@
73
75
  "react-dom": "^18.3.1",
74
76
  "shadcn": "^4.11.0",
75
77
  "tailwind-merge": "^3.6.0",
76
- "tw-animate-css": "^1.4.0"
78
+ "tw-animate-css": "^1.4.0",
79
+ "zod": "^3.25.76"
77
80
  },
78
81
  "devDependencies": {
79
82
  "@tailwindcss/postcss": "^4.3.1",