agencyhandy-mcp 1.7.2 → 1.8.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/.env.example CHANGED
@@ -8,6 +8,10 @@ AGENCY_BACKEND_API_KEY=
8
8
  # AGENCY_COMPANY_ID= # normally decoded from API key JWT
9
9
  # AGENCY_WORKSPACE_ID=
10
10
  # AGENCY_BACKEND_TIMEOUT_MS=45000
11
- # AGENCY_MCP_MAX_RPM=120 # in-process tool call rate limit
11
+ # AGENCY_MCP_MAX_RPM=120 # tool call rate limit per workspace member
12
+ # AGENCY_MCP_MAX_BODY_BYTES=1048576 # HTTP JSON body cap
13
+ # AGENCY_MCP_CORS_ORIGINS= # empty = no CORS; comma origins or *
12
14
  # AGENCY_MCP_STRICT_API_KEY=1 # require JWT exp (default on when NODE_ENV=production)
15
+ # TRANSPORT=http # stdio (default) or http
16
+ # PORT=3000
13
17
  # NODE_ENV=production
package/PRODUCTION.md CHANGED
@@ -5,22 +5,38 @@ Repo: https://github.com/AgencyHandy/agency-backend-mcp
5
5
 
6
6
  ## End-user flow
7
7
 
8
+ **Local host** (Cursor / Claude Desktop on a laptop):
9
+
8
10
  1. Agency Handy → **Workspace Config → API Key** → Generate
9
11
  2. Copy MCP config (key filled in once)
10
12
  3. Paste into Cursor `.mcp.json` or Claude Desktop config
11
13
  4. Restart host (Node.js 20+)
12
14
 
15
+ **Cloud agent** (Cloudflare Workers, Vercel, n8n, hosted Claude/Cursor): point at the hosted server below, same API key as a Bearer token. Nothing to install.
16
+
17
+ ## Hosted deployment
18
+
19
+ Live at **`https://mcp.agencyhandy.com/`**, running `TRANSPORT=http` behind nginx.
20
+
21
+ | | |
22
+ |---|---|
23
+ | MCP endpoint | `POST https://mcp.agencyhandy.com/` — the **root** path |
24
+ | Health | `GET https://mcp.agencyhandy.com/health` |
25
+ | Auth | `Authorization: Bearer <workspace API key>`; the JWT must carry `_id` and `company` |
26
+
27
+ The root path is the server's own route (`startHttp` in `src/server.js`), not a proxy rewrite — so it is the same path whether you use ours or self-host. If it ever moves, the README, this file, and the in-app config UI all need updating together: those three are what customers copy from.
28
+
13
29
  ## Ship checklist
14
30
 
15
- 1. Push this repo to GitHub
16
- 2. `npm publish --access public` (so `npx -y agencyhandy-mcp@1` works)
31
+ 1. Push this repo to GitHub — done
32
+ 2. `npm publish --access public` (so `npx -y agencyhandy-mcp@1` works) — **npm is still on 1.7.2**; 1.8.0 is unpublished, so stdio users lag the hosted server
17
33
  3. Merge/deploy ah-client PR that shows the MCP copy UI on the API Key tab
18
34
 
19
35
  ## Runtime guarantees
20
36
 
21
37
  - Fail fast on missing / placeholder / expired API keys
22
38
  - Stderr JSON audit logs (stdout = MCP protocol only)
23
- - Secret redaction, rate limit (120 RPM), one retry on 502/503
39
+ - Secret redaction, per-member rate limit (120 RPM), 1 MiB HTTP body cap, CORS off by default, one retry on 502/503
24
40
  - `companyid` from JWT; `ah_health` probes backend
25
41
  - Writes allowlisted: CRM (+ custom fields), work assign/status, invoices (+send), proposals, orders (create/update/assign)
26
42
  - Owner digest: `ah_dashboard_digest`
@@ -28,6 +44,7 @@ Repo: https://github.com/AgencyHandy/agency-backend-mcp
28
44
 
29
45
  ## Version
30
46
 
47
+ `1.8.0` — Streamable HTTP remote hosting (`TRANSPORT=http`, `POST /` with per-request Bearer JWT). Per-member rate limit, JSON body cap, CORS allowlist, HTTP unit tests.
31
48
  `1.7.2` — API builder context resource (`ah://api-context`): leads/orders/tasks/comments/labels/clients/invoices/vouchers/forms gotchas + unit/mutation tests.
32
49
  `1.7.1` — Security harden (SSRF path/url guards, axios/deps audit clean) + mutation/npx entry tests; owner insights tolerate null/sparse API rows.
33
50
  `1.7.0` — Owner insights: cash risk, proposal pipeline aging, lead segments, client churn heuristics; plus advanced context packs.
package/README.md CHANGED
@@ -1,19 +1,23 @@
1
1
  # Agency Handy MCP
2
2
 
3
+ [![npm](https://img.shields.io/npm/v/agencyhandy-mcp)](https://www.npmjs.com/package/agencyhandy-mcp)
4
+ [![license](https://img.shields.io/npm/l/agencyhandy-mcp)](LICENSE)
5
+
3
6
  Official [Model Context Protocol](https://modelcontextprotocol.io) server for **Agency Handy**.
4
7
 
5
8
  Connect Claude Desktop, Cursor, or any MCP host to your Agency Handy workspace: inspect proposals, projects, tickets, invoices, and create leads & clients — using your existing workspace API key.
6
9
 
7
10
  | | |
8
11
  |---|---|
9
- | **npm** | `agencyhandy-mcp` (publish after this repo is set up) |
12
+ | **npm** | `agencyhandy-mcp` |
10
13
  | **Node** | ≥ 20 |
11
- | **Auth** | Workspace API key (`x-api-key`) from Agency Handy |
14
+ | **Transports** | stdio (local) · Streamable HTTP (remote) |
15
+ | **Auth** | Workspace API key (JWT) from Agency Handy |
12
16
  | **API** | Your Agency Handy backend (`AGENCY_BACKEND_URL`) |
13
17
 
14
18
  ---
15
19
 
16
- ## Quick start (Agency Handy users)
20
+ ## Quick start
17
21
 
18
22
  1. In Agency Handy go to **Workspace Config → API Key**
19
23
  2. **Generate** a key (or use one you already saved)
@@ -41,7 +45,9 @@ Connect Claude Desktop, Cursor, or any MCP host to your Agency Handy workspace:
41
45
 
42
46
  > Prefer the in-app config: it fills the correct API base URL for your environment (production, staging, etc.).
43
47
 
44
- Until the package is on npm, developers can run from this repo:
48
+ **Running your agent in the cloud** — Cloudflare Workers, Vercel, n8n, a hosted Claude or Cursor — where there's no local process to spawn? Skip this and point at the [hosted server](#option-a--use-the-hosted-server-no-install) instead.
49
+
50
+ To run from a clone of this repo instead of npm:
45
51
 
46
52
  ```json
47
53
  {
@@ -60,16 +66,132 @@ Until the package is on npm, developers can run from this repo:
60
66
 
61
67
  ---
62
68
 
63
- ## What you can do
69
+ ## Transport modes
64
70
 
65
- ### Product naming → API
71
+ | Mode | When to use | How it works |
72
+ |------|-------------|--------------|
73
+ | **stdio** (default) | Local development, single user | MCP host spawns the server as a child process. API key lives in env. |
74
+ | **Streamable HTTP** | Cloud agents, multi-user, team access | Hosted for you at `https://mcp.agencyhandy.com/` (or run your own). Each client connects via `POST /` with a Bearer token. |
66
75
 
67
- | In Agency Handy | Backend |
68
- |-----------------|---------|
69
- | Proposal | Quotations |
70
- | Project | Orders (`pid`) |
71
- | Ticket | Tasks with `type=issue` |
72
- | Task | Tasks with `type=task` |
76
+ ---
77
+
78
+ ## Remote hosting (HTTP mode)
79
+
80
+ Two ways to run over HTTP: use the server Agency Handy hosts, or run your own.
81
+
82
+ ### Option A — use the hosted server (no install)
83
+
84
+ Agency Handy runs this server for you at **`https://mcp.agencyhandy.com/`**. Cloud-hosted agents — Cloudflare Workers, Vercel functions, n8n, or any MCP host that can't spawn a local process — connect straight to it with their workspace API key. Nothing to install, no server to keep up.
85
+
86
+ - **MCP endpoint:** `POST https://mcp.agencyhandy.com/` (the root path)
87
+ - **Health:** `GET https://mcp.agencyhandy.com/health`
88
+
89
+ **Cursor** (and any client that sends custom headers):
90
+
91
+ ```json
92
+ {
93
+ "mcpServers": {
94
+ "agency-handy": {
95
+ "url": "https://mcp.agencyhandy.com/",
96
+ "headers": {
97
+ "Authorization": "Bearer YOUR_API_KEY"
98
+ }
99
+ }
100
+ }
101
+ }
102
+ ```
103
+
104
+ **Claude Desktop** — bridge with `mcp-remote`, since it can't send custom headers:
105
+
106
+ ```json
107
+ {
108
+ "mcpServers": {
109
+ "agency-handy": {
110
+ "command": "npx",
111
+ "args": [
112
+ "-y", "mcp-remote",
113
+ "https://mcp.agencyhandy.com/",
114
+ "--header", "Authorization:Bearer YOUR_API_KEY"
115
+ ]
116
+ }
117
+ }
118
+ }
119
+ ```
120
+
121
+ **Claude Code:**
122
+
123
+ ```bash
124
+ claude mcp add agency-handy --transport http https://mcp.agencyhandy.com/ \
125
+ --header "Authorization: Bearer YOUR_API_KEY"
126
+ ```
127
+
128
+ Get the key from **Workspace Config → API Key**. Every request authenticates on its own — the server stores no keys, and `companyid` comes from the JWT.
129
+
130
+ ### Option B — run your own
131
+
132
+ Run the MCP server as an HTTP service on your own host.
133
+
134
+ #### 1. Start the server
135
+
136
+ ```bash
137
+ # npm
138
+ TRANSPORT=http npm start
139
+
140
+ # Docker
141
+ docker build -t agencyhandy-mcp .
142
+ docker run -p 3000:3000 \
143
+ -e AGENCY_BACKEND_URL=https://api.agencyhandy.com \
144
+ agencyhandy-mcp
145
+ ```
146
+
147
+ The server listens on `POST /` (Streamable HTTP) and `GET /health`.
148
+
149
+ #### 2. Connect clients
150
+
151
+ Each client passes their own Agency Handy API key as a Bearer token.
152
+
153
+ **Claude Desktop** — uses `mcp-remote` bridge (Claude Desktop doesn't support custom headers natively):
154
+
155
+ ```json
156
+ {
157
+ "mcpServers": {
158
+ "agency-handy": {
159
+ "command": "npx",
160
+ "args": [
161
+ "-y", "mcp-remote",
162
+ "https://your-server.com/",
163
+ "--header", "Authorization:Bearer YOUR_API_KEY"
164
+ ]
165
+ }
166
+ }
167
+ }
168
+ ```
169
+
170
+ **Cursor** — supports headers natively:
171
+
172
+ ```json
173
+ {
174
+ "mcpServers": {
175
+ "agency-handy": {
176
+ "url": "https://your-server.com/",
177
+ "headers": {
178
+ "Authorization": "Bearer YOUR_API_KEY"
179
+ }
180
+ }
181
+ }
182
+ }
183
+ ```
184
+
185
+ **Claude Code** — pass headers via CLI:
186
+
187
+ ```bash
188
+ claude mcp add agency-handy --transport http https://your-server.com/ \
189
+ --header "Authorization: Bearer YOUR_API_KEY"
190
+ ```
191
+
192
+ ---
193
+
194
+ ## Tools
73
195
 
74
196
  ### Write tools
75
197
 
@@ -98,7 +220,7 @@ Until the package is on npm, developers can run from this repo:
98
220
  | `ah_work_assign` | Add/remove ticket or task assignees |
99
221
  | `ah_work_set_status` | Move ticket/task board status |
100
222
 
101
- **Owner digest (read)**
223
+ ### Owner insights
102
224
 
103
225
  | Tool | Purpose |
104
226
  |------|---------|
@@ -107,25 +229,6 @@ Until the package is on npm, developers can run from this repo:
107
229
  | `ah_proposal_pipeline` | Waiting / stale / expiring proposals |
108
230
  | `ah_lead_segments` | Lead counts by status, source, optional custom field |
109
231
  | `ah_client_churn_risk` | Heuristic churn score (overdue + quiet orders) |
110
- | `ah_member_resolve` | Name/email → DB memberId (`unique` / `ambiguous` / `none`) — never invent ids |
111
- | `ah_status_resolve` | Status label → DB statusId — required before `ah_work_set_status` |
112
- | `ah_custom_field_list` | Workspace custom field definitions (lead/client/task) |
113
- | `ah_custom_field_seed_types` | Platform seed types (usually auto-resolved by create) |
114
- | `ah_member_custom_fields` | Member profile + custom field values |
115
- | `ah_task_context` / `ah_ticket_context` | Work item + **who to assign** (ranked candidates, order team/PM, workload) |
116
- | `ah_order_context` / `ah_project_context` | Order pack: tasks, tickets, files, related invoices/subscriptions |
117
- | `ah_proposal_context` | Proposal summary + comments + public + linked service |
118
- | `ah_invoice_context` | Invoice summary + public + linked order + related invoices |
119
-
120
- **Resolve rule:** If `ambiguous` or `none`, ask the user. Only assign/update with an id returned from these tools (or a user-confirmed match).
121
-
122
- **Assigning work**
123
-
124
- 1. `ah_task_context` / `ah_ticket_context` (pass `pid` when known)
125
- 2. Read `assignment.assignmentCandidates` + `assignment.advice`
126
- 3. `ah_work_assign` with a real `memberId` from candidates (or `ah_member_resolve` if the user named someone)
127
-
128
- **Owner insights**
129
232
 
130
233
  | Ask | Tool |
131
234
  |---|---|
@@ -135,7 +238,23 @@ Until the package is on npm, developers can run from this repo:
135
238
  | Quiet + overdue clients — watchlist & one next action | `ah_client_churn_risk` → order/invoice context |
136
239
  | Monday pulse: cash + cold proposals + slipping work | `ah_dashboard_digest` + the tools above |
137
240
 
138
- **Custom fields**
241
+ ### Read tools (highlights)
242
+
243
+ - **Health:** `ah_ping`, `ah_health`
244
+ - **Resolve:** `ah_member_resolve`, `ah_status_resolve` — never invent ObjectIds
245
+ - **Context packs:** `ah_proposal_context`, `ah_project_context`, `ah_ticket_context`, `ah_task_context`, `ah_invoice_context`, `ah_chat_context`, `ah_webhook_context`
246
+ - **Lists / gets:** proposals, projects, tickets, tasks, invoices, members, client companies, services, forms, dashboard
247
+ - **Platform:** chat, email-to-ticket settings, webhooks, order & platform subscriptions
248
+
249
+ **Resolve rule:** If `ambiguous` or `none`, ask the user. Only assign/update with an id returned from these tools (or a user-confirmed match).
250
+
251
+ **Assigning work:**
252
+
253
+ 1. `ah_task_context` / `ah_ticket_context` (pass `pid` when known)
254
+ 2. Read `assignment.assignmentCandidates` + `assignment.advice`
255
+ 3. `ah_work_assign` with a real `memberId` from candidates (or `ah_member_resolve` if the user named someone)
256
+
257
+ ### Custom fields
139
258
 
140
259
  Lead and client custom fields are **separate** catalogs (same display name may exist once per owner).
141
260
 
@@ -145,7 +264,19 @@ Lead and client custom fields are **separate** catalogs (same display name may e
145
264
  4. Admins can create definitions with `ah_custom_field_create` (name + type; options required for selects)
146
265
  5. **Duplicates:** creating a field whose name already exists for that owner (case/spacing ignored) returns `notCreatedCustomFields` with reason `Field already exists` — reuse the existing id instead
147
266
 
148
- **Lead example**
267
+ ### Product naming → API
268
+
269
+ | In Agency Handy | Backend |
270
+ |-----------------|---------|
271
+ | Proposal | Quotations |
272
+ | Project | Orders (`pid`) |
273
+ | Ticket | Tasks with `type=issue` |
274
+ | Task | Tasks with `type=task` |
275
+
276
+ ### Examples
277
+
278
+ <details>
279
+ <summary><strong>Lead</strong></summary>
149
280
 
150
281
  ```json
151
282
  {
@@ -156,8 +287,10 @@ Lead and client custom fields are **separate** catalogs (same display name may e
156
287
  "sendInvitationEmail": false
157
288
  }
158
289
  ```
290
+ </details>
159
291
 
160
- **Client example**
292
+ <details>
293
+ <summary><strong>Client</strong></summary>
161
294
 
162
295
  ```json
163
296
  {
@@ -166,8 +299,10 @@ Lead and client custom fields are **separate** catalogs (same display name may e
166
299
  "sendInvitationEmail": false
167
300
  }
168
301
  ```
302
+ </details>
169
303
 
170
- **Client company example**
304
+ <details>
305
+ <summary><strong>Client company</strong></summary>
171
306
 
172
307
  ```json
173
308
  {
@@ -176,8 +311,10 @@ Lead and client custom fields are **separate** catalogs (same display name may e
176
311
  "city": "Dhaka"
177
312
  }
178
313
  ```
314
+ </details>
179
315
 
180
- **Ticket example**
316
+ <details>
317
+ <summary><strong>Ticket</strong></summary>
181
318
 
182
319
  ```json
183
320
  {
@@ -188,8 +325,10 @@ Lead and client custom fields are **separate** catalogs (same display name may e
188
325
  "visibility": "client"
189
326
  }
190
327
  ```
328
+ </details>
191
329
 
192
- **Invoice example**
330
+ <details>
331
+ <summary><strong>Invoice</strong></summary>
193
332
 
194
333
  ```json
195
334
  {
@@ -199,23 +338,19 @@ Lead and client custom fields are **separate** catalogs (same display name may e
199
338
  "additionalFields": [{ "name": "Design", "quantity": 1, "value": 500 }]
200
339
  }
201
340
  ```
341
+ </details>
202
342
 
203
343
  Order create is intentionally omitted (multipart / service-package heavy). Use `ah_order_update` for existing orders.
204
344
 
205
- ### Read tools (highlights)
206
-
207
- - **Health:** `ah_ping`, `ah_health`
208
- - **Context packs:** `ah_proposal_context`, `ah_project_context`, `ah_ticket_context`, `ah_task_context`, `ah_invoice_context`, `ah_chat_context`, `ah_webhook_context`
209
- - **Lists / gets:** proposals, projects, tickets, tasks, invoices, members, client companies, services, forms, dashboard
210
- - **Platform:** chat, email-to-ticket settings, webhooks, order & platform subscriptions
345
+ ---
211
346
 
212
- Prefer `*_context` tools and the `ah://full-context` resource before inventing ObjectIds. For custom API tooling, also read `ah://api-context` (leads/orders/tasks/comments/labels/clients/invoices/vouchers/forms gotchas).
347
+ ## Resources & prompts
213
348
 
214
- ### Resources & prompts
349
+ **Resources:** `ah://full-context`, `ah://glossary`, `ah://models`, `ah://fields`, `ah://workflows`, `ah://workflows-platform`, `ah://api-context`, `ah://usage`
215
350
 
216
- Resources: `ah://full-context`, `ah://glossary`, `ah://models`, `ah://fields`, `ah://workflows`, `ah://workflows-platform`, `ah://api-context`, `ah://usage`, …
351
+ Prefer `*_context` tools and the `ah://full-context` resource before inventing ObjectIds. For custom API tooling, also read `ah://api-context` (leads/orders/tasks/comments/labels/clients/invoices/vouchers/forms gotchas).
217
352
 
218
- Prompts: `agency_handy_orientation`, `investigate_ticket`, `investigate_project`, `investigate_proposal`, `investigate_task`
353
+ **Prompts:** `agency_handy_orientation`, `investigate_ticket`, `investigate_project`, `investigate_proposal`, `investigate_task`
219
354
 
220
355
  ---
221
356
 
@@ -224,11 +359,15 @@ Prompts: `agency_handy_orientation`, `investigate_ticket`, `investigate_project`
224
359
  | Variable | Required | Description |
225
360
  |----------|----------|-------------|
226
361
  | `AGENCY_BACKEND_URL` | yes | API origin, e.g. `https://api.agencyhandy.com` (no `/api/v1` suffix) |
227
- | `AGENCY_BACKEND_API_KEY` | yes | Member API JWT from Workspace Config → API Key |
362
+ | `AGENCY_BACKEND_API_KEY` | stdio: yes / HTTP: no | Member API JWT. Required for stdio mode. For HTTP mode, clients provide it per-connection via Bearer token. |
363
+ | `TRANSPORT` | no | `stdio` (default) or `http` (Streamable HTTP) |
364
+ | `PORT` | no | HTTP mode listen port (default `3000`) |
228
365
  | `AGENCY_COMPANY_ID` | no | Override; normally taken from the JWT `company` claim |
229
366
  | `AGENCY_WORKSPACE_ID` | no | Optional workspace hint for tools that accept it |
230
367
  | `AGENCY_BACKEND_TIMEOUT_MS` | no | Default `45000` |
231
- | `AGENCY_MCP_MAX_RPM` | no | Tool rate limit per process (default `120`) |
368
+ | `AGENCY_MCP_MAX_RPM` | no | Tool rate limit **per workspace member** (default `120`) |
369
+ | `AGENCY_MCP_MAX_BODY_BYTES` | no | HTTP JSON body cap (default `1048576`) |
370
+ | `AGENCY_MCP_CORS_ORIGINS` | no | Comma-separated browser origins, or `*`. Empty = no CORS (default) |
232
371
  | `AGENCY_MCP_STRICT_API_KEY` | no | `1` to require JWT `exp`; on by default when `NODE_ENV=production` |
233
372
  | `NODE_ENV` | no | Set `production` for hosts |
234
373
 
@@ -236,7 +375,18 @@ Copy `.env.example` → `.env` for local development.
236
375
 
237
376
  ---
238
377
 
239
- ## Develop
378
+ ## Security
379
+
380
+ - The API key is a **full workspace credential** — treat it like a password
381
+ - Never commit `.env` or paste keys into public chats
382
+ - Rotate keys in Agency Handy if leaked
383
+ - **stdio mode:** local trust — the MCP host spawns the server directly
384
+ - **HTTP mode:** each request authenticates via Bearer JWT (mapped to `x-api-key`); rate-limited per workspace member; JSON body capped; CORS off unless `AGENCY_MCP_CORS_ORIGINS` is set; no session state persisted
385
+ - Allowed writes are limited to lead / client / client-company create, tickets, tasks, invoices, proposals, orders, comments, and work assign/status
386
+
387
+ ---
388
+
389
+ ## Development
240
390
 
241
391
  ```bash
242
392
  git clone https://github.com/AgencyHandy/agency-backend-mcp.git
@@ -264,16 +414,6 @@ See [PRODUCTION.md](./PRODUCTION.md) for the operator checklist.
264
414
 
265
415
  ---
266
416
 
267
- ## Security
268
-
269
- - The API key is a **full workspace credential** — treat it like a password
270
- - Never commit `.env` or paste keys into public chats
271
- - Rotate keys in Agency Handy if leaked
272
- - MCP is **stdio / local-trust**; do not expose it on a public network without extra auth
273
- - Allowed writes are limited to lead / client / client-company create
274
-
275
- ---
276
-
277
417
  ## License
278
418
 
279
419
  UNLICENSED — Agency Handy proprietary.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agencyhandy-mcp",
3
- "version": "1.7.2",
3
+ "version": "1.8.0",
4
4
  "description": "Official Agency Handy MCP server — owner insights, context packs, API builder context",
5
5
  "type": "module",
6
6
  "main": "src/server.js",
@@ -18,8 +18,10 @@
18
18
  ],
19
19
  "scripts": {
20
20
  "start": "node src/server.js",
21
+ "start:remote": "TRANSPORT=http node src/server.js",
21
22
  "dev": "node --watch src/server.js",
22
- "test": "node scripts/smoke.mjs && node scripts/unit-api-context.mjs && node scripts/unit-custom-fields.mjs && node scripts/unit-work-context.mjs && node scripts/unit-owner-insights.mjs && node scripts/unit-security-mutate.mjs",
23
+ "test": "node scripts/smoke.mjs && node scripts/unit-api-context.mjs && node scripts/unit-custom-fields.mjs && node scripts/unit-work-context.mjs && node scripts/unit-owner-insights.mjs && node scripts/unit-security-mutate.mjs && node scripts/unit-http.mjs",
24
+ "test:http": "node scripts/unit-http.mjs",
23
25
  "test:security": "node scripts/unit-security-mutate.mjs",
24
26
  "test:api-context": "node scripts/unit-api-context.mjs",
25
27
  "test:live": "SMOKE_LIVE=1 node scripts/smoke.mjs",
package/src/lib.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import axios from "axios";
2
2
  import { z } from "zod";
3
3
 
4
- export const VERSION = "1.7.2";
4
+ export const VERSION = "1.8.0";
5
5
 
6
6
  export const READ_ONLY = false;
7
7
 
@@ -247,14 +247,49 @@ export function validateApiKey(apiKey, { requireExp = false } = {}) {
247
247
  };
248
248
  }
249
249
 
250
- export function createRateLimiter({ maxPerMinute = 120 } = {}) {
250
+ export function rateLimitKey(keyCheck) {
251
+ if (keyCheck?.companyId && keyCheck?.memberId) {
252
+ return `${keyCheck.companyId}:${keyCheck.memberId}`;
253
+ }
254
+ return "global";
255
+ }
256
+
257
+ /**
258
+ * Sliding-window limiter. Pass a tenant key so HTTP mode cannot starve
259
+ * other workspaces from one shared bucket.
260
+ */
261
+ export function createRateLimiter({ maxPerMinute = 120, maxBuckets = 10_000 } = {}) {
251
262
  const windowMs = 60_000;
252
- const hits = [];
263
+ const buckets = new Map();
264
+
265
+ function prune(hits, now) {
266
+ while (hits.length && hits[0] <= now - windowMs) hits.shift();
267
+ }
268
+
269
+ function gc(now) {
270
+ if (buckets.size < maxBuckets) return;
271
+ for (const [key, hits] of buckets) {
272
+ prune(hits, now);
273
+ if (hits.length === 0) buckets.delete(key);
274
+ }
275
+ while (buckets.size >= maxBuckets) {
276
+ const oldest = buckets.keys().next().value;
277
+ if (oldest == null) break;
278
+ buckets.delete(oldest);
279
+ }
280
+ }
281
+
253
282
  return {
254
283
  maxPerMinute,
255
- tryConsume() {
284
+ tryConsume(key = "global") {
256
285
  const now = Date.now();
257
- while (hits.length && hits[0] <= now - windowMs) hits.shift();
286
+ gc(now);
287
+ let hits = buckets.get(key);
288
+ if (!hits) {
289
+ hits = [];
290
+ buckets.set(key, hits);
291
+ }
292
+ prune(hits, now);
258
293
  if (hits.length >= maxPerMinute) {
259
294
  return {
260
295
  ok: false,
package/src/server.js CHANGED
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
  import path from "node:path";
3
+ import http from "node:http";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import dotenv from "dotenv";
5
6
  import { z } from "zod";
6
7
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
8
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
8
10
  import {
9
11
  CallToolRequestSchema,
10
12
  GetPromptRequestSchema,
@@ -21,6 +23,7 @@ import {
21
23
  createRateLimiter,
22
24
  logEvent,
23
25
  optionalNonEmptyString,
26
+ rateLimitKey,
24
27
  validateApiKey,
25
28
  } from "./lib.js";
26
29
  import { PROMPTS, getPrompt } from "./prompts.js";
@@ -28,12 +31,13 @@ import { RESOURCES, readResource } from "./resources.js";
28
31
  import { handleTool, tools } from "./tools.js";
29
32
 
30
33
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
31
- // Never override real process env (CI / host injects secrets).
32
34
  dotenv.config({ path: path.join(__dirname, "..", ".env"), override: false });
33
35
 
36
+ const TRANSPORT = (process.env.TRANSPORT || "stdio").toLowerCase();
37
+
34
38
  const envSchema = z.object({
35
39
  AGENCY_BACKEND_URL: z.string().url(),
36
- AGENCY_BACKEND_API_KEY: z.string().min(1),
40
+ AGENCY_BACKEND_API_KEY: optionalNonEmptyString,
37
41
  AGENCY_WORKSPACE_ID: optionalNonEmptyString,
38
42
  AGENCY_COMPANY_ID: optionalNonEmptyString,
39
43
  AGENCY_BACKEND_TIMEOUT_MS: optionalNonEmptyString,
@@ -51,7 +55,7 @@ if (!envResult.success) {
51
55
  })),
52
56
  });
53
57
  process.stderr.write(
54
- "[agencyhandy-mcp] Invalid environment. Set AGENCY_BACKEND_URL and AGENCY_BACKEND_API_KEY.\n"
58
+ "[agencyhandy-mcp] Invalid environment. Set AGENCY_BACKEND_URL.\n"
55
59
  );
56
60
  process.exit(1);
57
61
  }
@@ -66,124 +70,349 @@ if (!urlCheck.ok) {
66
70
  env.AGENCY_BACKEND_URL = urlCheck.url;
67
71
 
68
72
  const strictKey =
69
- env.AGENCY_MCP_STRICT_API_KEY === "1" ||
70
- env.NODE_ENV === "production";
71
- const keyCheck = validateApiKey(env.AGENCY_BACKEND_API_KEY, {
72
- requireExp: strictKey,
73
- });
74
- if (!keyCheck.ok) {
75
- logEvent("error", "api_key_invalid", { error: keyCheck.error });
76
- process.stderr.write(`[agencyhandy-mcp] ${keyCheck.error}\n`);
77
- process.exit(1);
78
- }
73
+ env.AGENCY_MCP_STRICT_API_KEY === "1" || env.NODE_ENV === "production";
79
74
 
80
- const api = createApi(env);
81
75
  const rateLimiter = createRateLimiter({
82
- maxPerMinute: Math.max(10, Number(env.AGENCY_MCP_MAX_RPM) || 120),
76
+ maxPerMinute: Math.max(1, Number(env.AGENCY_MCP_MAX_RPM) || 120),
83
77
  });
84
78
 
79
+ const MAX_BODY_BYTES = Math.max(
80
+ 1024,
81
+ Number(process.env.AGENCY_MCP_MAX_BODY_BYTES) || 1_048_576
82
+ );
83
+
85
84
  logEvent("info", "server_starting", {
85
+ mode: TRANSPORT,
86
86
  backendBaseUrl: env.AGENCY_BACKEND_URL,
87
- companyId: keyCheck.companyId,
88
- memberId: keyCheck.memberId,
89
87
  maxRpm: rateLimiter.maxPerMinute,
90
88
  toolCount: tools.length,
91
89
  });
92
90
 
93
- const server = new Server(
94
- {
95
- name: "agency-handy",
96
- version: VERSION,
97
- },
98
- {
99
- capabilities: {
100
- tools: {},
101
- resources: {},
102
- prompts: {},
103
- },
104
- instructions: `Agency Handy backend MCP (production).
91
+ // ── HTTP helpers ──────────────────────────────────────────────────────────────
92
+
93
+ function extractBearerToken(req) {
94
+ const auth = req.headers["authorization"];
95
+ if (!auth) return null;
96
+ const match = auth.match(/^Bearer\s+(.+)$/i);
97
+ return match ? match[1].trim() : null;
98
+ }
99
+
100
+ function declaredBodyTooLarge(req) {
101
+ const n = Number(req.headers["content-length"]);
102
+ return Number.isFinite(n) && n > MAX_BODY_BYTES;
103
+ }
104
+
105
+ async function parseJsonBody(req, { maxBytes = MAX_BODY_BYTES } = {}) {
106
+ return new Promise((resolve, reject) => {
107
+ const chunks = [];
108
+ let size = 0;
109
+ let settled = false;
110
+ const fail = (err) => {
111
+ if (settled) return;
112
+ settled = true;
113
+ reject(err);
114
+ };
115
+ req.on("data", (chunk) => {
116
+ if (settled) return;
117
+ size += chunk.length;
118
+ if (size > maxBytes) {
119
+ const err = new Error("payload_too_large");
120
+ err.code = "PAYLOAD_TOO_LARGE";
121
+ req.destroy();
122
+ fail(err);
123
+ return;
124
+ }
125
+ chunks.push(chunk);
126
+ });
127
+ req.on("end", () => {
128
+ if (settled) return;
129
+ settled = true;
130
+ const raw = Buffer.concat(chunks).toString("utf8");
131
+ if (!raw) return resolve(null);
132
+ try {
133
+ resolve(JSON.parse(raw));
134
+ } catch {
135
+ reject(new Error("Invalid JSON"));
136
+ }
137
+ });
138
+ req.on("error", fail);
139
+ });
140
+ }
141
+
142
+ function sendJson(res, status, body) {
143
+ res.writeHead(status, {
144
+ "Content-Type": "application/json",
145
+ "Cache-Control": "no-cache",
146
+ });
147
+ res.end(JSON.stringify(body));
148
+ }
149
+
150
+ function sendError(res, status, message) {
151
+ sendJson(res, status, { error: message });
152
+ }
153
+
154
+ // ── MCP Server factory (per-connection in HTTP mode) ──────────────────────────
155
+
156
+ function createMcpServer(apiClient, connEnv, connKeyCheck) {
157
+ const server = new Server(
158
+ { name: "agency-handy", version: VERSION },
159
+ {
160
+ capabilities: { tools: {}, resources: {}, prompts: {} },
161
+ instructions: `Agency Handy backend MCP (production).
105
162
  Read ah://full-context first. Prefer *_context tools.
106
163
  NEVER invent ObjectIds. For people: ah_member_resolve → unique or user pick → then assign.
107
164
  For board labels: ah_status_resolve → then ah_work_set_status.
108
165
  Prefer ah_dashboard_digest for morning briefings. Call ah_health if connectivity is unclear.`,
109
- }
110
- );
166
+ }
167
+ );
111
168
 
112
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
169
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
113
170
 
114
- server.setRequestHandler(ListResourcesRequestSchema, async () => ({
115
- resources: RESOURCES,
116
- }));
171
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({
172
+ resources: RESOURCES,
173
+ }));
117
174
 
118
- server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
119
- const result = readResource(request.params.uri);
120
- if (!result) {
121
- throw new Error(`Unknown resource: ${request.params.uri}`);
175
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
176
+ const result = readResource(request.params.uri);
177
+ if (!result) throw new Error(`Unknown resource: ${request.params.uri}`);
178
+ return result;
179
+ });
180
+
181
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
182
+ prompts: PROMPTS,
183
+ }));
184
+
185
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
186
+ const result = getPrompt(
187
+ request.params.name,
188
+ request.params.arguments || {}
189
+ );
190
+ if (!result) throw new Error(`Unknown prompt: ${request.params.name}`);
191
+ return result;
192
+ });
193
+
194
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
195
+ const name = request.params.name;
196
+ const started = Date.now();
197
+ const limited = rateLimiter.tryConsume(rateLimitKey(connKeyCheck));
198
+ if (!limited.ok) {
199
+ logEvent("warn", "rate_limited", { tool: name });
200
+ return asText({
201
+ ok: false,
202
+ error: "rate_limited",
203
+ message: `Too many tool calls. Retry after ~${Math.ceil(limited.retryAfterMs / 1000)}s.`,
204
+ retryAfterMs: limited.retryAfterMs,
205
+ });
206
+ }
207
+
208
+ try {
209
+ const result = await handleTool(name, request.params.arguments ?? {}, {
210
+ api: apiClient,
211
+ env: connEnv,
212
+ keyCheck: connKeyCheck,
213
+ });
214
+ logEvent("info", "tool_ok", { tool: name, ms: Date.now() - started });
215
+ return result;
216
+ } catch (error) {
217
+ logEvent("error", "tool_error", {
218
+ tool: name,
219
+ ms: Date.now() - started,
220
+ message: error?.message || "Unknown error",
221
+ });
222
+ if (error?.name === "ZodError") {
223
+ return asText({
224
+ ok: false,
225
+ error: "Invalid tool arguments",
226
+ details: error.issues,
227
+ });
228
+ }
229
+ return asText({
230
+ ok: false,
231
+ error: "Tool handler failed",
232
+ message: error?.message || "Unknown error",
233
+ });
234
+ }
235
+ });
236
+
237
+ return server;
238
+ }
239
+
240
+ // ── Streamable HTTP handler ───────────────────────────────────────────────────
241
+
242
+ async function handleMcpPost(req, res) {
243
+ const token = extractBearerToken(req);
244
+ if (!token) {
245
+ logEvent("warn", "http_missing_auth");
246
+ res.setHeader("WWW-Authenticate", 'Bearer realm="agencyhandy-mcp"');
247
+ return sendError(
248
+ res,
249
+ 401,
250
+ "Missing Authorization header (Bearer token required)"
251
+ );
122
252
  }
123
- return result;
124
- });
125
253
 
126
- server.setRequestHandler(ListPromptsRequestSchema, async () => ({
127
- prompts: PROMPTS,
128
- }));
254
+ const keyCheck = validateApiKey(token, { requireExp: strictKey });
255
+ if (!keyCheck.ok) {
256
+ logEvent("warn", "http_invalid_key", { error: keyCheck.error });
257
+ return sendError(res, 401, `Invalid API key: ${keyCheck.error}`);
258
+ }
129
259
 
130
- server.setRequestHandler(GetPromptRequestSchema, async (request) => {
131
- const result = getPrompt(
132
- request.params.name,
133
- request.params.arguments || {}
134
- );
135
- if (!result) {
136
- throw new Error(`Unknown prompt: ${request.params.name}`);
260
+ if (declaredBodyTooLarge(req)) {
261
+ return sendError(res, 413, "Request body too large");
137
262
  }
138
- return result;
139
- });
140
263
 
141
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
142
- const name = request.params.name;
143
- const started = Date.now();
144
- const limited = rateLimiter.tryConsume();
145
- if (!limited.ok) {
146
- logEvent("warn", "rate_limited", { tool: name });
147
- return asText({
148
- ok: false,
149
- error: "rate_limited",
150
- message: `Too many tool calls. Retry after ~${Math.ceil(limited.retryAfterMs / 1000)}s.`,
151
- retryAfterMs: limited.retryAfterMs,
152
- });
264
+ let body;
265
+ try {
266
+ body = await parseJsonBody(req);
267
+ } catch (err) {
268
+ if (err?.code === "PAYLOAD_TOO_LARGE") {
269
+ return sendError(res, 413, "Request body too large");
270
+ }
271
+ return sendError(res, 400, "Invalid JSON body");
272
+ }
273
+
274
+ if (!body) {
275
+ return sendError(res, 400, "Empty request body");
153
276
  }
154
277
 
278
+ const connEnv = { ...env, AGENCY_BACKEND_API_KEY: token };
279
+ const apiClient = createApi(connEnv);
280
+
281
+ logEvent("info", "http_connection", {
282
+ memberId: keyCheck.memberId,
283
+ companyId: keyCheck.companyId,
284
+ });
285
+
286
+ const server = createMcpServer(apiClient, connEnv, keyCheck);
287
+ const transport = new StreamableHTTPServerTransport({
288
+ sessionIdGenerator: undefined,
289
+ });
290
+
155
291
  try {
156
- const result = await handleTool(name, request.params.arguments ?? {}, {
157
- api,
158
- env,
159
- keyCheck,
160
- });
161
- logEvent("info", "tool_ok", {
162
- tool: name,
163
- ms: Date.now() - started,
164
- });
165
- return result;
292
+ await server.connect(transport);
293
+ await transport.handleRequest(req, res, body);
166
294
  } catch (error) {
167
- logEvent("error", "tool_error", {
168
- tool: name,
169
- ms: Date.now() - started,
295
+ logEvent("error", "http_transport_error", {
170
296
  message: error?.message || "Unknown error",
171
297
  });
172
- if (error?.name === "ZodError") {
173
- return asText({
174
- ok: false,
175
- error: "Invalid tool arguments",
176
- details: error.issues,
177
- });
298
+ if (!res.headersSent) {
299
+ sendError(res, 500, "Internal server error");
178
300
  }
179
- return asText({
180
- ok: false,
181
- error: "Tool handler failed",
182
- message: error?.message || "Unknown error",
183
- });
184
301
  }
185
- });
302
+ }
303
+
304
+ function corsAllowOrigin(req) {
305
+ const raw = (process.env.AGENCY_MCP_CORS_ORIGINS || "").trim();
306
+ if (!raw) return null;
307
+ if (raw === "*") return "*";
308
+ const requestOrigin = req.headers.origin;
309
+ if (!requestOrigin) return null;
310
+ const allowed = raw.split(",").map((s) => s.trim()).filter(Boolean);
311
+ return allowed.includes(requestOrigin) ? requestOrigin : null;
312
+ }
313
+
314
+ function applyCors(req, res) {
315
+ const origin = corsAllowOrigin(req);
316
+ if (!origin) return false;
317
+ res.setHeader("Access-Control-Allow-Origin", origin);
318
+ res.setHeader("Vary", "Origin");
319
+ res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
320
+ res.setHeader(
321
+ "Access-Control-Allow-Headers",
322
+ "Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version"
323
+ );
324
+ res.setHeader("Access-Control-Max-Age", "86400");
325
+ return true;
326
+ }
327
+
328
+ // ── Mode: stdio ───────────────────────────────────────────────────────────────
329
+
330
+ async function startStdio() {
331
+ if (!env.AGENCY_BACKEND_API_KEY) {
332
+ process.stderr.write(
333
+ "[agencyhandy-mcp] AGENCY_BACKEND_API_KEY required for stdio mode.\n"
334
+ );
335
+ process.exit(1);
336
+ }
337
+
338
+ const keyCheck = validateApiKey(env.AGENCY_BACKEND_API_KEY, {
339
+ requireExp: strictKey,
340
+ });
341
+ if (!keyCheck.ok) {
342
+ logEvent("error", "api_key_invalid", { error: keyCheck.error });
343
+ process.stderr.write(`[agencyhandy-mcp] ${keyCheck.error}\n`);
344
+ process.exit(1);
345
+ }
346
+
347
+ const api = createApi(env);
348
+
349
+ logEvent("info", "stdio_config", {
350
+ backendBaseUrl: env.AGENCY_BACKEND_URL,
351
+ companyId: keyCheck.companyId,
352
+ memberId: keyCheck.memberId,
353
+ });
354
+
355
+ const server = createMcpServer(api, env, keyCheck);
356
+ const transport = new StdioServerTransport();
357
+ await server.connect(transport);
358
+ logEvent("info", "server_ready", { version: VERSION, mode: "stdio" });
359
+ }
186
360
 
187
- const transport = new StdioServerTransport();
188
- await server.connect(transport);
189
- logEvent("info", "server_ready", { version: VERSION });
361
+ // ── Mode: Streamable HTTP ─────────────────────────────────────────────────────
362
+
363
+ function startHttp() {
364
+ const parsedPort = Number(process.env.PORT);
365
+ const listenPort =
366
+ Number.isFinite(parsedPort) && parsedPort >= 0 ? parsedPort : 3000;
367
+
368
+ const httpServer = http.createServer(async (req, res) => {
369
+ applyCors(req, res);
370
+
371
+ if (req.method === "OPTIONS") {
372
+ res.writeHead(204);
373
+ return res.end();
374
+ }
375
+
376
+ const url = new URL(req.url, `http://${req.headers.host || "localhost"}`);
377
+
378
+ if (url.pathname === "/health" && req.method === "GET") {
379
+ return sendJson(res, 200, {
380
+ ok: true,
381
+ version: VERSION,
382
+ mode: TRANSPORT,
383
+ backendUrl: env.AGENCY_BACKEND_URL,
384
+ });
385
+ }
386
+
387
+ if (url.pathname === "/" && req.method === "POST") {
388
+ return handleMcpPost(req, res);
389
+ }
390
+
391
+ if (url.pathname === "/" && req.method === "GET") {
392
+ return sendError(
393
+ res,
394
+ 405,
395
+ "GET not supported. Use POST with Streamable HTTP."
396
+ );
397
+ }
398
+
399
+ sendError(res, 404, "Not found");
400
+ });
401
+
402
+ httpServer.listen(listenPort, () => {
403
+ const addr = httpServer.address();
404
+ const bound = typeof addr === "object" && addr ? addr.port : listenPort;
405
+ logEvent("info", "http_listening", { port: bound, version: VERSION });
406
+ process.stderr.write(
407
+ `[agencyhandy-mcp] Streamable HTTP listening on :${bound} (POST /)\n`
408
+ );
409
+ });
410
+ }
411
+
412
+ // ── Start ─────────────────────────────────────────────────────────────────────
413
+
414
+ if (TRANSPORT === "http") {
415
+ startHttp();
416
+ } else {
417
+ await startStdio();
418
+ }