@daileyos/mcp-server 1.21.0 → 1.21.2

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/.dockerignore +6 -0
  2. package/Dockerfile +19 -0
  3. package/dist/api.d.ts.map +1 -1
  4. package/dist/api.js +14 -1
  5. package/dist/api.js.map +1 -1
  6. package/dist/context.d.ts +8 -0
  7. package/dist/context.d.ts.map +1 -0
  8. package/dist/context.js +6 -0
  9. package/dist/context.js.map +1 -0
  10. package/dist/http.d.ts +5 -0
  11. package/dist/http.d.ts.map +1 -0
  12. package/dist/http.js +193 -0
  13. package/dist/http.js.map +1 -0
  14. package/dist/index.js +8 -146
  15. package/dist/index.js.map +1 -1
  16. package/dist/server.d.ts +9 -0
  17. package/dist/server.d.ts.map +1 -0
  18. package/dist/server.js +165 -0
  19. package/dist/server.js.map +1 -0
  20. package/dist/tools/accounts.d.ts +4 -1
  21. package/dist/tools/accounts.d.ts.map +1 -1
  22. package/dist/tools/accounts.js +56 -52
  23. package/dist/tools/accounts.js.map +1 -1
  24. package/dist/tools/wordpress-targeting.d.ts.map +1 -1
  25. package/dist/tools/wordpress-targeting.js +22 -7
  26. package/dist/tools/wordpress-targeting.js.map +1 -1
  27. package/docs/superpowers/plans/2026-08-09-remote-mcp-endpoint.md +663 -0
  28. package/docs/superpowers/specs/2026-08-09-remote-mcp-endpoint-design.md +66 -0
  29. package/package.json +6 -4
  30. package/src/api.ts +9 -1
  31. package/src/context.ts +12 -0
  32. package/src/http.ts +160 -0
  33. package/src/index.ts +8 -161
  34. package/src/server.ts +188 -0
  35. package/src/tools/accounts.ts +69 -61
  36. package/src/tools/wordpress-targeting.ts +22 -7
  37. package/test/context.test.ts +36 -0
  38. package/test/http.test.ts +103 -0
  39. package/test/server-surface.test.ts +36 -0
  40. package/test/use-account-sticky.test.ts +28 -0
  41. package/test/wordpress-targeting.test.ts +36 -1
  42. package/dist/tools/buddy.d.ts +0 -3
  43. package/dist/tools/buddy.d.ts.map +0 -1
  44. package/dist/tools/buddy.js +0 -765
  45. package/dist/tools/buddy.js.map +0 -1
  46. package/dist/tools/payments.d.ts +0 -3
  47. package/dist/tools/payments.d.ts.map +0 -1
  48. package/dist/tools/payments.js +0 -96
  49. package/dist/tools/payments.js.map +0 -1
  50. package/dist/tools/redis.d.ts +0 -3
  51. package/dist/tools/redis.d.ts.map +0 -1
  52. package/dist/tools/redis.js +0 -72
  53. package/dist/tools/redis.js.map +0 -1
@@ -0,0 +1,66 @@
1
+ # Remote MCP endpoint — mcp.dailey.cloud (design)
2
+
3
+ Approved by Jonny 2026-08-09 (brainstorm in ops session). v1 = bearer-token auth; Core OAuth 2.1 is phase 2, out of scope here.
4
+
5
+ ## Goal
6
+ Expose the existing DOS MCP tools over streamable HTTP at `https://mcp.dailey.cloud` so remote-capable clients (Cursor, claude.ai, ChatGPT connectors) attach with a URL + DOS API token — no local install. The npm stdio package (`@daileyos/mcp-server`) keeps working unchanged.
7
+
8
+ ## Decisions (locked)
9
+ - **Tool surface:** everything except `registerAdminTools` and the account-SWITCH tool. **AMENDED during implementation (2026-08-09):** `registerAuthTools` was originally excluded on the premise it held device-login/config flows — inspection shows its three tools (`dailey_whoami`, `dailey_auth_status`, `dailey_auth_enable`) are pure API calls, so they SHIP remotely (whoami/auth_status are how a remote user verifies their connection). The `includeLocalAuth` build flag remains for any future genuinely-local tool. Project-transfer tools also ship remotely (customer capability; capi-authorized consent flow). capi remains the sole authorizer.
10
+ - **Tokens:** existing DOS API tokens (same value `DAILEY_API_TOKEN` takes today; users copy from the dashboard). No new token type in v1.
11
+ - **Hosting:** normal DOS project (internal account), repo-first from this repo, domain `mcp.dailey.cloud`, 1 replica.
12
+ - **Transport:** streamable HTTP, **stateless mode** (`sessionIdGenerator: undefined`) — all tools are request/response; restarts invisible; no session store.
13
+
14
+ ## Architecture
15
+ One repo (`dailey-mcp`), two entries sharing one assembly:
16
+
17
+ - `src/server.ts` (new): `buildServer(opts: { includeAdmin: boolean, includeLocalAuth: boolean }): McpServer` — moves the register-call block out of `index.ts` verbatim; gates `registerAdminTools` on `includeAdmin` and `registerAuthTools` on `includeLocalAuth`. `index.ts` keeps its version-check/active-account behavior and calls `buildServer({ includeAdmin: true, includeLocalAuth: true })` — stdio behavior byte-identical.
18
+ - `src/http.ts` (new): node `http` server.
19
+ - `POST /mcp` → SDK `StreamableHTTPServerTransport` (stateless), one `buildServer({ includeAdmin: false, includeLocalAuth: false })` + transport per request (stateless pattern), request handling wrapped in the token context (below).
20
+ - `GET /` → minimal HTML: what this is, how to attach (Cursor/claude.ai snippets), link to docs.
21
+ - `GET /healthz` → 200 `ok`.
22
+ - `GET /.well-known/oauth-protected-resource` → static JSON naming `https://core.dailey.cloud` as the (future) authorization server; contract-correct stub so OAuth-capable clients discover cleanly in phase 2.
23
+ - CORS: `Access-Control-Allow-Origin: *`, allow `Authorization, Content-Type, Mcp-Session-Id, MCP-Protocol-Version`; handle `OPTIONS`.
24
+ - `DELETE /mcp` and `GET /mcp` → 405 (stateless mode has no sessions / no server-push stream).
25
+
26
+ ## Per-request auth (the one real mechanism)
27
+ `src/api.ts` gains an `AsyncLocalStorage<{ token: string }>` exported as `tokenContext`. `resolveToken()` checks `tokenContext.getStore()?.token` FIRST, then falls back to today's env/config chain. `http.ts`:
28
+ 1. Reads `Authorization: Bearer <token>`; missing/malformed → HTTP 401, `WWW-Authenticate: Bearer resource_metadata="https://mcp.dailey.cloud/.well-known/oauth-protected-resource"`, JSON-RPC error body.
29
+ 2. Valid shape → `tokenContext.run({ token }, () => transport.handleRequest(...))`.
30
+ 3. No token validation at the MCP layer — a bad token surfaces as capi's 401 through the existing `formatError` path on first tool call.
31
+ Zero changes to the 41 tool modules.
32
+
33
+ ## Security (v1 posture — reviewed and expanded 2026-08-09 at Jonny's direction)
34
+ **Core property: the server is credential-free.** It holds no API keys, no DB creds, no service tokens — bearer tokens arrive per-request, live only in the request's AsyncLocalStorage, and die with it. A fully compromised pod yields no standing secrets. Preserve this property in all future changes (nothing secret in env/ConfigMap/Secret for this workload).
35
+
36
+ - Admin, account-switch, and project-transfer tools never registered on the remote surface (auth tools SHIP per the amended Decisions — pure API calls).
37
+ - In-process per-token rate limit: 60 requests/min (fixed window, `Map<tokenHash, {count, windowStart}>`); over-limit → HTTP 429. Token keys are sha256 truncations — raw tokens never held beyond the request, never logged.
38
+ - No request-body logging; access log line = method, path, status, duration, token hash prefix (8 chars), and tool name when the request is a tools/call (NEVER tool arguments — they can contain user secrets). Errors returned to clients never echo the token.
39
+ - Request body cap: 1 MiB (413 above). Server timeouts: headersTimeout 10s, requestTimeout 120s (long tool calls allowed; slowloris not).
40
+ - Global ceiling in addition to per-token: 600 req/min process-wide → 429 + `Retry-After` (protects capi from a runaway or distributed client).
41
+ - CORS `*` is safe here BECAUSE auth is an explicit header (no cookies → no CSRF); revisit if cookie auth ever appears. Validate `Content-Type: application/json` on POST /mcp.
42
+ - Container hardening: non-root `USER node`, `readOnlyRootFilesystem: true` in the deployment (SDK needs no disk writes), no added capabilities, `NODE_ENV=production`.
43
+ - Dependency hygiene: `@modelcontextprotocol/sdk` pinned exact (no `^`); `npm audit --omit=dev` in the build (fail on critical).
44
+ - Tool OUTPUTS are untrusted data to the calling model (they can contain customer-authored content from capi); nothing in this server treats them as instructions — inherent MCP posture, noted so future middleware doesn't.
45
+ - **Active-account state (three moves, decided 2026-08-09 after review):**
46
+ 1. Remote surface registers the account-LIST tool but NOT the account-SWITCH tool (stateless mode has no session to remember it; a manager with two connectors could otherwise cross-wire accounts with valid creds). The list tool's remote description instructs "pass `account:` per call" (supported on every tool since v1.21.0).
47
+ 2. The AsyncLocalStorage store is `{ token: string, account?: string }`. `setActiveAccount()`/`getActiveAccount()` consult the ALS store FIRST (write/read request-scoped state when present) and fall through to the module global only when no store exists (stdio). Cross-user bleed becomes impossible by construction — any code path that "sets the account" inside a remote request affects only that request.
48
+ 3. Fix `wordpress-live-edit.ts:62`, which mutates the global as a side effect of its per-call `account` param — route it through the same mechanism (this is a latent stdio bug too: a per-call param permanently switching the session's account).
49
+
50
+ ## Deployment
51
+ - `Dockerfile` (new, repo root): node:22-alpine, `npm ci && npm run build`, `CMD ["node", "dist/http.js"]`, `EXPOSE 8080` (`PORT` env honored, default 8080).
52
+ - DOS project `dailey-mcp-remote` (internal account) built from this repo's main; domain `mcp.dailey.cloud`; resources 100m/128Mi req, 500m/512Mi lim.
53
+ - The container reaches capi via the public `https://os.dailey.cloud/api` (default `DAILEY_API_URL`) — no in-cluster coupling, no netpol work (customer-ns egress to public IPs is allowed).
54
+
55
+ ## Error handling
56
+ - 401 (no/malformed bearer) and 429 (rate limit) at HTTP layer with JSON-RPC-shaped bodies.
57
+ - Everything else flows through the SDK transport; tool errors keep the existing `formatError`/`remediationFor` copy (already plain-language).
58
+ - Uncaught handler errors → 500 JSON-RPC internal error; process stays up (per-request try/catch).
59
+
60
+ ## Testing
61
+ 1. **Unit** (`test/`): `resolveToken()` prefers tokenContext over env; `buildServer({includeAdmin:false})` registers no `dailey_admin_*` and no login tools; rate limiter windows.
62
+ 2. **Integration** (local): start `dist/http.js`, connect with `@modelcontextprotocol/sdk` `StreamableHTTPClientTransport` + `Authorization` header, `tools/list` (assert no admin tools, count > 40), call `dailey_whoami` with a real token (env-gated test), assert identity echo.
63
+ 3. **Live**: deploy → `curl /healthz` → attach from Cursor by URL → tool list + `dailey_whoami` + one read tool (`dailey_list_projects`).
64
+
65
+ ## Out of scope (phase 2+)
66
+ Core OAuth 2.1 (authorization-server work in dailey-core, dynamic client registration, PKCE); scoped MCP-specific tokens + revocation UI; docs-site "Add to Cursor" deep-link buttons; MCP registry listings.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@daileyos/mcp-server",
3
- "version": "1.21.0",
3
+ "version": "1.21.2",
4
4
  "description": "Dailey OS MCP server for Claude Code and AI assistants",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -8,16 +8,18 @@
8
8
  "dailey-mcp": "./dist/index.js"
9
9
  },
10
10
  "scripts": {
11
- "build": "tsc",
11
+ "build": "tsc && chmod +x dist/index.js",
12
12
  "start": "node dist/index.js",
13
- "test": "tsx --test --experimental-test-module-mocks test/*.test.ts"
13
+ "test": "tsx --test --experimental-test-module-mocks test/*.test.ts",
14
+ "prepublishOnly": "npm run build && test -x dist/index.js",
15
+ "start:http": "node dist/http.js"
14
16
  },
15
17
  "publishConfig": {
16
18
  "access": "public"
17
19
  },
18
20
  "dependencies": {
19
21
  "@daileyos/wp-bundle": "^0.1.0",
20
- "@modelcontextprotocol/sdk": "^1.12.1",
22
+ "@modelcontextprotocol/sdk": "1.27.1",
21
23
  "zod": "^3.24.4"
22
24
  },
23
25
  "devDependencies": {
package/src/api.ts CHANGED
@@ -2,6 +2,7 @@ import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
3
  import { readFileSync } from 'node:fs';
4
4
  import { OWN_VERSION } from './version.js';
5
+ import { requestContext } from './context.js';
5
6
 
6
7
  const API_URL = process.env.DAILEY_API_URL || 'https://os.dailey.cloud/api';
7
8
  const DAILEY_EMAIL = process.env.DAILEY_EMAIL;
@@ -42,6 +43,8 @@ const ENV_TOKEN = process.env.DAILEY_API_TOKEN || '';
42
43
  let refreshedToken = '';
43
44
 
44
45
  export function resolveToken(): string {
46
+ const ctx = requestContext.getStore();
47
+ if (ctx) return ctx.token;
45
48
  if (ENV_TOKEN) return ENV_TOKEN;
46
49
  if (refreshedToken) return refreshedToken;
47
50
  return readCliStoredToken() || '';
@@ -58,10 +61,15 @@ export function resolveToken(): string {
58
61
  let activeAccount: string | undefined;
59
62
 
60
63
  export function setActiveAccount(slugOrId: string | undefined): void {
61
- activeAccount = slugOrId && slugOrId.trim() ? slugOrId.trim() : undefined;
64
+ const v = slugOrId && slugOrId.trim() ? slugOrId.trim() : undefined;
65
+ const ctx = requestContext.getStore();
66
+ if (ctx) { ctx.account = v; return; } // request-scoped: dies with the request
67
+ activeAccount = v;
62
68
  }
63
69
 
64
70
  export function getActiveAccount(): string | undefined {
71
+ const ctx = requestContext.getStore();
72
+ if (ctx) return ctx.account;
65
73
  return activeAccount;
66
74
  }
67
75
 
package/src/context.ts ADDED
@@ -0,0 +1,12 @@
1
+ // Request-scoped identity for the remote (HTTP) entry. The stdio entry never
2
+ // enters this context, so api.ts falls through to its module-global/env logic
3
+ // there — stdio behavior is unchanged by construction.
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+
6
+ export interface RequestIdentity {
7
+ token: string;
8
+ /** Managed-account scope for THIS request only (X-Dailey-Account). */
9
+ account?: string;
10
+ }
11
+
12
+ export const requestContext = new AsyncLocalStorage<RequestIdentity>();
package/src/http.ts ADDED
@@ -0,0 +1,160 @@
1
+ import http from 'node:http';
2
+ import { createHash } from 'node:crypto';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
5
+ import { buildServer } from './server.js';
6
+ import { requestContext } from './context.js';
7
+
8
+ const PORT = Number(process.env.PORT || 8080);
9
+ const BODY_LIMIT = 1024 * 1024; // 1 MiB
10
+ const PER_TOKEN_LIMIT = 60; // req/min
11
+ const GLOBAL_LIMIT = 600; // req/min
12
+ const RESOURCE = 'https://mcp.dailey.cloud';
13
+ const AUTH_SERVER = 'https://core.dailey.cloud';
14
+
15
+ // In-flight cap: each request retains a ~1.2MB McpServer until close; 50 × ~1.2MB bounds worst-case heap under slow tool calls (512Mi pod). Security-review dissent 2026-08-09.
16
+ export const MAX_INFLIGHT = 50;
17
+ let inflight = 0;
18
+
19
+ // ── fixed-window rate limiting ──────────────────────────────────────────────
20
+ const tokenWindows = new Map<string, { count: number; windowStart: number }>();
21
+ let globalWindow = { count: 0, windowStart: Date.now() };
22
+ function allow(tokenHash: string): 'ok' | 'token' | 'global' {
23
+ const now = Date.now();
24
+ if (now - globalWindow.windowStart >= 60_000) globalWindow = { count: 0, windowStart: now };
25
+ if (++globalWindow.count > GLOBAL_LIMIT) return 'global';
26
+ const w = tokenWindows.get(tokenHash);
27
+ if (!w || now - w.windowStart >= 60_000) { tokenWindows.set(tokenHash, { count: 1, windowStart: now }); return 'ok'; }
28
+ return ++w.count <= PER_TOKEN_LIMIT ? 'ok' : 'token';
29
+ }
30
+ setInterval(() => { // stop the map growing forever
31
+ const cutoff = Date.now() - 120_000;
32
+ for (const [k, w] of tokenWindows) if (w.windowStart < cutoff) tokenWindows.delete(k);
33
+ }, 60_000).unref();
34
+
35
+ function hashToken(token: string): string {
36
+ return createHash('sha256').update(token).digest('hex');
37
+ }
38
+
39
+ function cors(res: http.ServerResponse): void {
40
+ res.setHeader('Access-Control-Allow-Origin', '*');
41
+ res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
42
+ res.setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, Mcp-Session-Id, MCP-Protocol-Version');
43
+ }
44
+
45
+ function json(res: http.ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
46
+ cors(res);
47
+ res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
48
+ res.end(JSON.stringify(body));
49
+ }
50
+
51
+ function rpcError(res: http.ServerResponse, status: number, code: number, message: string, headers: Record<string, string> = {}): void {
52
+ json(res, status, { jsonrpc: '2.0', error: { code, message }, id: null }, headers);
53
+ res.destroy();
54
+ }
55
+
56
+ function readBody(req: http.IncomingMessage): Promise<string | null> {
57
+ return new Promise((resolve) => {
58
+ let size = 0; const chunks: Buffer[] = [];
59
+ req.on('data', (c: Buffer) => {
60
+ size += c.length;
61
+ if (size > BODY_LIMIT) { resolve(null); req.destroy(); return; }
62
+ chunks.push(c);
63
+ });
64
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
65
+ req.on('error', () => resolve(null));
66
+ });
67
+ }
68
+
69
+ const LANDING = `<!doctype html><title>Dailey OS MCP</title>
70
+ <h1>Dailey OS remote MCP endpoint</h1>
71
+ <p>Point your MCP client at <code>${RESOURCE}/mcp</code> with header
72
+ <code>Authorization: Bearer &lt;your DOS API token&gt;</code> (copy the token from the
73
+ <a href="https://os.dailey.cloud">dashboard</a>). Docs: <a href="https://docs.dailey.cloud">docs.dailey.cloud</a>.</p>`;
74
+
75
+ export function createHttpServer(): http.Server {
76
+ const server = http.createServer(async (req, res) => {
77
+ const started = Date.now();
78
+ const url = (req.url || '/').split('?')[0];
79
+ let logSuffix = '';
80
+ const finish = (status: number) => {
81
+ // access log: method path status duration token-hash tool — never bodies/args
82
+ console.log(`${req.method} ${url} ${status} ${Date.now() - started}ms${logSuffix}`);
83
+ };
84
+ res.on('finish', () => finish(res.statusCode));
85
+ try {
86
+ if (req.method === 'OPTIONS') { cors(res); res.writeHead(204); res.end(); return; }
87
+ if (url === '/healthz') { cors(res); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('ok'); return; }
88
+ if (url === '/' && req.method === 'GET') { cors(res); res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(LANDING); return; }
89
+ if (url === '/.well-known/oauth-protected-resource') {
90
+ json(res, 200, { resource: RESOURCE, authorization_servers: [AUTH_SERVER], bearer_methods_supported: ['header'] });
91
+ return;
92
+ }
93
+ if (url !== '/mcp') { rpcError(res, 404, -32601, 'Not found'); return; }
94
+ if (req.method !== 'POST') { rpcError(res, 405, -32601, 'Stateless server: only POST /mcp is supported'); return; }
95
+
96
+ const auth = req.headers.authorization || '';
97
+ const m = /^Bearer\s+(\S+)$/i.exec(auth);
98
+ if (!m) {
99
+ rpcError(res, 401, -32001, 'Missing bearer token. Get a DOS API token from https://os.dailey.cloud and send Authorization: Bearer <token>.',
100
+ { 'WWW-Authenticate': `Bearer resource_metadata="${RESOURCE}/.well-known/oauth-protected-resource"` });
101
+ return;
102
+ }
103
+ const token = m[1];
104
+ const tokenHash = hashToken(token);
105
+ logSuffix = ` tok=${tokenHash.slice(0, 8)}`;
106
+
107
+ const verdict = allow(tokenHash);
108
+ if (verdict !== 'ok') {
109
+ const message = verdict === 'token'
110
+ ? 'Rate limit exceeded (60/min per token). Slow down.'
111
+ : 'Server-wide rate limit exceeded. Retry shortly.';
112
+ rpcError(res, 429, -32000, message, { 'Retry-After': '30' }); return;
113
+ }
114
+ if (inflight >= MAX_INFLIGHT) {
115
+ rpcError(res, 503, -32000, 'Server busy (too many concurrent requests). Retry shortly.', { 'Retry-After': '5' });
116
+ return;
117
+ }
118
+ inflight++;
119
+ const done = () => { inflight = Math.max(0, inflight - 1); };
120
+ res.once('close', done);
121
+ if (!/^application\/json/i.test(req.headers['content-type'] || '')) {
122
+ rpcError(res, 415, -32600, 'Content-Type must be application/json'); return;
123
+ }
124
+ const raw = await readBody(req);
125
+ if (raw === null) { rpcError(res, 413, -32600, 'Body too large (limit 1 MiB)'); return; }
126
+ let parsed: unknown;
127
+ try { parsed = JSON.parse(raw); } catch { rpcError(res, 400, -32700, 'Parse error'); return; }
128
+ const toolName = ((parsed as any)?.method === 'tools/call' ? String((parsed as any)?.params?.name ?? '') : '').replace(/[^\w.-]/g, '').slice(0, 64);
129
+ if (toolName) logSuffix += ` tool=${toolName}`;
130
+
131
+ // Stateless: fresh server+transport per request; identity lives in ALS.
132
+ const mcp = buildServer({ includeAdmin: false, includeLocalAuth: true, includeAccountSwitch: false });
133
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
134
+ cors(res);
135
+ res.on('error', () => {});
136
+ res.on('close', () => { transport.close().catch(() => {}); mcp.close().catch(() => {}); });
137
+ await requestContext.run({ token }, async () => {
138
+ await mcp.connect(transport);
139
+ await transport.handleRequest(req, res, parsed);
140
+ });
141
+ } catch (err) {
142
+ console.error('handler error:', (err as Error).message);
143
+ if (!res.headersSent) rpcError(res, 500, -32603, 'Internal error');
144
+ else res.end();
145
+ }
146
+ });
147
+ server.headersTimeout = 10_000;
148
+ server.requestTimeout = 120_000;
149
+ server.keepAliveTimeout = 65_000;
150
+ server.maxConnections = 1000;
151
+ return server;
152
+ }
153
+
154
+ export function getInflight(): number {
155
+ return inflight;
156
+ }
157
+
158
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
159
+ createHttpServer().listen(PORT, () => console.log(`dailey-mcp http listening on :${PORT} (stateless streamable HTTP)`));
160
+ }
package/src/index.ts CHANGED
@@ -1,52 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
4
3
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
5
4
 
6
- import { z } from 'zod';
7
- import { hasCredentials, getActiveAccount, setActiveAccount } from './api.js';
5
+ import { hasCredentials } from './api.js';
8
6
  import { OWN_VERSION, checkForNewerVersion, outdatedNotice } from './version.js';
9
- import { registerAuthTools } from './tools/auth.js';
10
- import { registerAccountTools } from './tools/accounts.js';
11
- import { registerProjectTools } from './tools/projects.js';
12
- import { registerDeployTools } from './tools/deploy.js';
13
- import { registerDeployStatusTools } from './tools/deploy-status.js';
14
- import { registerBuildLogsTools } from './tools/build-logs.js';
15
- import { registerScaleTools } from './tools/scale.js';
16
- import { registerEnvTools } from './tools/env.js';
17
- import { registerDomainTools } from './tools/domains.js';
18
- import { registerDbTools } from './tools/db.js';
19
- import { registerMigrateTools } from './tools/db-migrate.js';
20
- import { registerExecRunTools } from './tools/exec-run.js';
21
- import { registerProjectTransferTools } from './tools/project-transfer.js';
22
- import { registerAdminTools } from './tools/admin.js';
23
- import { registerUsageTools } from './tools/usage.js';
24
- import { registerBillingTools } from './tools/billing.js';
25
- import { registerPlatformTools } from './tools/platform.js';
26
- import { registerStorageTools } from './tools/storage.js';
27
- import { registerAiTools } from './tools/ai.js';
28
- import { registerEmailTools } from './tools/email.js';
29
- import { registerCreditTools } from './tools/credits.js';
30
- import { registerAddonTools } from './tools/addons.js';
31
- import { registerDaileyImagesTools } from './tools/dailey-images.js';
32
- import { registerImageTools } from './tools/images.js';
33
- import { registerProcessTools } from './tools/processes.js';
34
- import { registerLifecycleTools } from './tools/lifecycle.js';
35
- import { registerBackupTools } from './tools/backups.js';
36
- import { registerWordPressMigrateTools } from './tools/wordpress-migrate.js';
37
- import { registerWordPressImportTools } from './tools/wordpress-import.js';
38
- import { registerWordPressSnapshotTools } from './tools/wordpress-snapshot.js';
39
- import { registerWordPressLiveEditTools } from './tools/wordpress-live-edit.js';
40
- import { registerWordPressTargetingTools } from './tools/wordpress-targeting.js';
41
- import { registerEnvironmentTools } from './tools/environments.js';
42
- import { registerResourceConfigTools } from './tools/resource-config.js';
43
- import { registerLinkTools } from './tools/links.js';
44
- import { registerCredentialRevealTools } from './tools/credentials-reveal.js';
45
- import { registerAnalyzeTools } from './tools/analyze.js';
46
- import { registerCliTools } from './tools/cli.js';
47
- import { registerBundleTools } from './tools/bundle.js';
48
- import { registerDiagnoseTools } from './tools/diagnose.js';
49
- import { registerSupportTools } from './tools/support.js';
7
+ import { buildServer } from './server.js';
50
8
 
51
9
  function writeStream(stream: NodeJS.WriteStream, text: string): Promise<void> {
52
10
  return new Promise((resolve) => {
@@ -125,123 +83,12 @@ if (newerVersion) {
125
83
  process.stderr.write(`dailey-mcp: v${OWN_VERSION} is outdated (latest v${newerVersion})\n`);
126
84
  }
127
85
 
128
- const server = new McpServer(
129
- {
130
- name: 'dailey-os',
131
- version: OWN_VERSION,
132
- },
133
- newerVersion ? { instructions: outdatedNotice(newerVersion) } : undefined,
134
- );
135
-
136
- // ─── Account-context hardening (2026-07-13, Muenda's "which account am I in?") ───
137
- // Two invariants, applied uniformly to ALL tools via this registration wrapper:
138
- // 1. Every tool accepts an optional `account` param — a STATELESS, per-call
139
- // scope to a managed account (set → run → restore). Agents no longer have
140
- // to rely on dailey_use_account session state being what they remember.
141
- // 2. Every tool result is prefixed with `[account: <effective>]` so the model
142
- // (and the human reading the transcript) always sees which account the
143
- // call actually ran against. Wrong-account work becomes visible instantly.
144
- // Tools that declare their own `account` param (the WP tools) keep their schema;
145
- // the wrapper still enforces the per-call set/restore around them.
146
- {
147
- const originalTool = server.tool.bind(server);
148
- (server as any).tool = (name: string, description: string, schema: Record<string, unknown>, handler: (...a: any[]) => any) => {
149
- const augmented = 'account' in schema
150
- ? schema
151
- : {
152
- ...schema,
153
- account: z.string().optional().describe(
154
- 'Managed-account slug to run THIS call against (per-call scope; overrides the dailey_use_account session state for this call only). Omit to use the current session account.',
155
- ),
156
- };
157
- return originalTool(name, description, augmented as any, async (args: any, extra: any) => {
158
- const requested: string | undefined =
159
- typeof args?.account === 'string' && args.account.trim() ? args.account.trim() : undefined;
160
- const prev = getActiveAccount();
161
- if (requested) setActiveAccount(requested);
162
- try {
163
- const result = await handler(args, extra);
164
- const effective = requested ?? getActiveAccount() ?? 'self (your own account)';
165
- if (result?.content?.length && result.content[0]?.type === 'text') {
166
- result.content[0].text = `[account: ${effective}]\n${result.content[0].text}`;
167
- }
168
- return result;
169
- } finally {
170
- // Restore ONLY when this call temporarily overrode the session scope —
171
- // dailey_use_account itself must keep its session-setting behavior.
172
- if (requested) setActiveAccount(prev);
173
- }
174
- });
175
- };
176
- }
177
-
178
- // Core + identity
179
- registerAuthTools(server);
180
- registerAccountTools(server);
181
- registerPlatformTools(server);
182
- registerUsageTools(server);
183
- registerBillingTools(server);
184
- // À-la-carte billing surfaces — prepaid credits + capacity add-ons.
185
- registerCreditTools(server);
186
- registerAddonTools(server);
187
-
188
- // Projects + deploys
189
- registerProjectTools(server);
190
- registerAnalyzeTools(server);
191
- registerDeployTools(server);
192
- registerDeployStatusTools(server);
193
- registerBuildLogsTools(server);
194
- registerImageTools(server);
195
-
196
- // Lifecycle + scaling
197
- registerScaleTools(server);
198
- registerLifecycleTools(server);
199
- registerResourceConfigTools(server);
200
- registerProcessTools(server);
201
-
202
- // Config
203
- registerEnvTools(server);
204
- registerDomainTools(server);
205
- registerLinkTools(server);
206
- registerCredentialRevealTools(server);
207
-
208
- // Data
209
- registerDbTools(server);
210
- registerMigrateTools(server);
211
- registerStorageTools(server);
212
- registerAiTools(server);
213
- registerEmailTools(server);
214
- registerDaileyImagesTools(server);
215
- registerBackupTools(server);
216
- registerWordPressMigrateTools(server);
217
- registerWordPressImportTools(server);
218
- registerWordPressSnapshotTools(server);
219
- // WordPress live-edit tools (files/media/wp-cli) wrapping customer-api#18's
220
- // tenant-scoped live-edit routes. Mutating ops are two-phase (preview → confirm_token).
221
- registerWordPressLiveEditTools(server);
222
- // Scenario 1 create + WP targeting spine (list/target), paired with the
223
- // customer-api targeting-spine deploy.
224
- registerWordPressTargetingTools(server);
225
- registerEnvironmentTools(server);
226
-
227
- // Runtime operations — exec into a pod, run one-off jobs
228
- registerExecRunTools(server);
229
-
230
- // Admin-only — customer onboarding, project transfer
231
- registerAdminTools(server);
232
- registerProjectTransferTools(server);
233
-
234
- // CLI assist
235
- registerCliTools(server);
236
-
237
- // Atomic deploy bundle
238
- registerBundleTools(server);
239
-
240
- // One-stop health check — first tool to reach for when something is broken
241
- registerDiagnoseTools(server);
242
-
243
- // Support — escalate to Dailey OS team
244
- registerSupportTools(server);
86
+ const server = buildServer({
87
+ includeAdmin: true,
88
+ includeLocalAuth: true,
89
+ includeAccountSwitch: true,
90
+ instructions: newerVersion ? outdatedNotice(newerVersion) : undefined,
91
+ });
245
92
 
246
93
  const transport = new StdioServerTransport();
247
94
  await server.connect(transport);