@harperfast/template-vue-studio 1.13.5 → 1.13.7

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 (36) hide show
  1. package/.agents/skills/harper-best-practices/AGENTS.md +1260 -1113
  2. package/.agents/skills/harper-best-practices/rules/automatic-apis.md +118 -83
  3. package/.agents/skills/harper-best-practices/rules/checking-authentication.md +244 -256
  4. package/.agents/skills/harper-best-practices/rules/custom-resources.md +37 -42
  5. package/.agents/skills/harper-best-practices/rules/defining-relationships.md +86 -49
  6. package/.agents/skills/harper-best-practices/rules/deploying-from-ci.md +163 -170
  7. package/.agents/skills/harper-best-practices/rules/deploying-to-harper-fabric.md +128 -88
  8. package/.agents/skills/harper-best-practices/rules/load-env.md +27 -30
  9. package/.agents/skills/harper-best-practices/rules/programmatic-table-requests.md +184 -155
  10. package/.agents/skills/harper-best-practices/rules/querying-rest-apis.md +146 -94
  11. package/.agents/skills/harper-best-practices/rules/schema-design-tooling.md +60 -77
  12. package/.agents/skills/harper-best-practices/rules/v5-upgrade.md +52 -63
  13. package/.agents/skills/harper-best-practices/rules/vector-indexing.md +77 -68
  14. package/.agents/skills/harper-mcp/AGENTS.md +228 -155
  15. package/.agents/skills/harper-mcp/rules/custom-mcp-tools.md +35 -41
  16. package/.agents/skills/harper-mcp/rules/enabling-mcp.md +104 -92
  17. package/.agents/skills/harper-mcp/rules/rate-limiting.md +95 -28
  18. package/agent/skills/harper-best-practices/AGENTS.md +1260 -1113
  19. package/agent/skills/harper-best-practices/rules/automatic-apis.md +118 -83
  20. package/agent/skills/harper-best-practices/rules/checking-authentication.md +244 -256
  21. package/agent/skills/harper-best-practices/rules/custom-resources.md +37 -42
  22. package/agent/skills/harper-best-practices/rules/defining-relationships.md +86 -49
  23. package/agent/skills/harper-best-practices/rules/deploying-from-ci.md +163 -170
  24. package/agent/skills/harper-best-practices/rules/deploying-to-harper-fabric.md +128 -88
  25. package/agent/skills/harper-best-practices/rules/load-env.md +27 -30
  26. package/agent/skills/harper-best-practices/rules/programmatic-table-requests.md +184 -155
  27. package/agent/skills/harper-best-practices/rules/querying-rest-apis.md +146 -94
  28. package/agent/skills/harper-best-practices/rules/schema-design-tooling.md +60 -77
  29. package/agent/skills/harper-best-practices/rules/v5-upgrade.md +52 -63
  30. package/agent/skills/harper-best-practices/rules/vector-indexing.md +77 -68
  31. package/agent/skills/harper-mcp/AGENTS.md +228 -155
  32. package/agent/skills/harper-mcp/rules/custom-mcp-tools.md +35 -41
  33. package/agent/skills/harper-mcp/rules/enabling-mcp.md +104 -92
  34. package/agent/skills/harper-mcp/rules/rate-limiting.md +95 -28
  35. package/package.json +1 -1
  36. package/skills-lock.json +2 -2
@@ -6,15 +6,15 @@ Guidelines for exposing a Harper instance as a Model Context Protocol (MCP) serv
6
6
 
7
7
  ### 1.1 Enabling and Configuring Harper MCP Server Profiles
8
8
 
9
- Instructions for the agent to enable and configure Harper's MCP server profiles (`operations` and `application`) using the `mcp:` block in `harper-config.yaml`.
9
+ Instructions for the agent to enable and configure Harper's MCP server profiles (`operations` and `application`) in `harper-config.yaml`.
10
10
 
11
11
  #### When to Use
12
12
 
13
- Apply this rule when adding MCP support to a Harper deployment so that LLM hosts (Claude Desktop, Cursor, Zed, custom agents) can discover and invoke Harper operations and resources. Use it when configuring rate limits, session lifecycle, allow/deny lists, or durable quota policies for either MCP profile. See [connecting-clients.md](connecting-clients.md) for wiring an MCP client to a running Harper instance.
13
+ Apply this rule when adding MCP support to a Harper deployment so that LLM hosts (Claude Desktop, Cursor, Zed, custom agents) can discover and invoke Harper operations and resources. Use it when configuring rate limits, session lifecycle, allow/deny lists, or durable quota policies for either MCP profile. See [connecting-clients.md](connecting-clients.md) for wiring an MCP host to a running Harper instance.
14
14
 
15
15
  #### How It Works
16
16
 
17
- 1. **Enable profiles via presence of their sub-block.** A profile is enabled by the **presence** of its sub-block under `mcp:` — there is no separate `enabled` flag. Add an empty map to enable a profile with all defaults:
17
+ 1. **Enable profiles via `presence`**: A profile is enabled by the **presence** of its sub-block under `mcp:` — there is no separate `enabled` flag. Add an empty block for each profile you want active:
18
18
 
19
19
  ```yaml
20
20
  mcp:
@@ -22,75 +22,106 @@ Apply this rule when adding MCP support to a Harper deployment so that LLM hosts
22
22
  application: {}
23
23
  ```
24
24
 
25
- - The `operations` profile mounts at `/mcp` on the **operations server** (default port `9925`).
26
- - The `application` profile mounts at `/mcp` on the **application HTTP server** (default port `9926`).
25
+ - `operations` mounts at `/mcp` on the **operations server** (default port `9925`).
26
+ - `application` mounts at `/mcp` on the **application HTTP server** (default port `9926`).
27
27
 
28
- 2. **Configure the operations profile (`mcp.operations`).** This profile wraps Harper's operation catalog.
28
+ 2. **Configure the operations profile** (`mcp.operations.*`): Control which operations are exposed as MCP tools.
29
29
 
30
- | Key | Type | Default | Purpose |
31
- | ----------- | ----------------- | --------- | -------------------------------------------------------------------------------- |
32
- | `mountPath` | `string` | `/mcp` | URL path the endpoint mounts on |
33
- | `allow` | `array<string>` | See below | Operations exposed as MCP tools (glob or literal); **replaces** the default list |
34
- | `deny` | `array<string>` | `[]` | Operations filtered out after `allow` is applied |
35
- | `maxTools` | `integer` (min 1) | `200` | Max tools per `tools/list` response page |
30
+ | Key | Type | Default | Purpose |
31
+ | ----------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
32
+ | `mountPath` | `string` | `/mcp` | URL path for the endpoint |
33
+ | `allow` | `array<string>` | `['describe_*', 'list_*', 'search_*', 'get_job', 'get_status', 'get_analytics', 'get_metrics', 'system_information', 'read_log', 'read_audit_log']` | Operations exposed as tools; **replaces** the default list |
34
+ | `deny` | `array<string>` | `[]` | Operations filtered out after `allow` is applied |
35
+ | `maxTools` | `integer` | `200` | Max tools per `tools/list` page |
36
36
 
37
- Default `allow` list:
37
+ Setting `mcp.operations.allow` **replaces** the default list entirely — it does not merge. To expose destructive operations (e.g. `set_configuration`, `drop_table`), add them explicitly. Do not add `get_*` as a glob — it exposes `get_configuration` (which can return TLS / S3 / authentication secrets) and other sensitive operations. Opt them in deliberately.
38
38
 
39
- ```yaml
40
- allow:
41
- - describe_*
42
- - list_*
43
- - search_*
44
- - get_job
45
- - get_status
46
- - get_analytics
47
- - get_metrics
48
- - system_information
49
- - read_log
50
- - read_audit_log
51
- ```
39
+ 3. **Configure the application profile** (`mcp.application.*`): Controls the endpoint that walks your exported `Resource` classes.
40
+
41
+ | Key | Type | Default | Purpose |
42
+ | ------------------ | --------- | ------- | ------------------------------------------------------------------ |
43
+ | `searchMaxResults` | `integer` | `1000` | Hard cap on records a `search_<resource>` tool can return per call |
52
44
 
53
- Setting `allow` **replaces** the default — it does not merge. To expose destructive operations (e.g. `set_configuration`, `drop_table`), add them explicitly.
45
+ All `mcp.operations.*` keys (`mountPath`, `allow`, `deny`, `maxTools`, `rateLimit.*`) also apply to `mcp.application`. Components can publish their own content under author-chosen URIs with a static `mcpResources` array.
54
46
 
55
- 3. **Configure the application profile (`mcp.application`).** This profile walks your exported `Resource` classes and generates one MCP tool per implemented REST verb. It accepts all `mcp.operations.*` keys plus:
47
+ 4. **Set rate limits** (`mcp.<profile>.rateLimit.*`): Token-bucket limits apply per `(session, tool)` pair and per session across all tools. Exhausted buckets return `result.isError = true` with `kind: "rate_limited"` — not a JSON-RPC transport error — so the LLM can back off gracefully. See [rate-limiting.md](rate-limiting.md) for broader context.
56
48
 
57
- | Key | Type | Default | Purpose |
58
- | ------------------ | ----------------- | ------- | ------------------------------------------------------------------ |
59
- | `searchMaxResults` | `integer` (min 1) | `1000` | Hard cap on records a `search_<resource>` tool can return per call |
49
+ | Key | Type | Default (operations / application) | Purpose |
50
+ | --------------------- | --------- | ----------------------------------- | ----------------------------------------------------------------- |
51
+ | `perToolPerSecond` | `number` | `10` / `25` | Sustained per-tool refill rate; `0` disables |
52
+ | `perToolBurst` | `number` | `20` / `50` | Burst capacity of the per-tool bucket |
53
+ | `sessionConcurrency` | `integer` | `25` / `50` | Max concurrent `tools/call` per session |
54
+ | `sessionPerSecond` | `number` | `100` / `200` | Sustained per-session rate across all tools |
55
+ | `perClientPerSecond` | `number` | `0` (disabled) | Sustained rate keyed on client identity (5.2.0+) |
56
+ | `perClientBurst` | `number` | `perClientPerSecond` floored at `1` | Burst capacity of the per-client bucket |
57
+ | `initializePerSecond` | `number` | `10` | Sustained session-creation rate per client identity; `0` disables |
58
+ | `initializeBurst` | `number` | `50` | Burst capacity of the `initialize` bucket |
59
+ | `identityHeader` | `string` | unset (socket IP) | Trusted header supplying client identity (e.g. `x-forwarded-for`) |
60
+ - `perClientPerSecond` survives session cycling — it is keyed on client identity, not session (5.2.0+).
61
+ - `initializePerSecond` is **on by default**; a denied `initialize` returns HTTP `429` with a `Retry-After` header and a JSON-RPC error body; no session is created.
62
+ - Only set `identityHeader` when the fronting proxy strips or replaces it on untrusted traffic.
60
63
 
61
- 4. **Set rate limits for each profile (`mcp.<profile>.rateLimit.*`).** Token-bucket limits apply per `(session, tool)` pair and per session overall. Exhausted buckets return `result.isError = true` with `kind: "rate_limited"` — not a JSON-RPC error. See [rate-limiting.md](rate-limiting.md) for broader context.
64
+ 5. **Configure session lifecycle** (`mcp.session.*`):
62
65
 
63
- | Key | Type | Default (operations) | Default (application) | Purpose |
64
- | -------------------- | ----------------- | ----------------------------------- | --------------------- | ----------------------------------------------------------------- |
65
- | `perToolPerSecond` | `number` (min 0) | `10` | `25` | Sustained per-tool refill rate; `0` disables |
66
- | `perToolBurst` | `number` (min 0) | `20` | `50` | Burst capacity of the per-tool bucket |
67
- | `sessionConcurrency` | `integer` (min 0) | `25` | `50` | Max concurrent `tools/call` per session |
68
- | `sessionPerSecond` | `number` (min 0) | `100` | `200` | Sustained per-session rate across all tools |
69
- | `perClientPerSecond` | `number` (min 0) | `0` (disabled) | `0` (disabled) | Sustained rate keyed on client identity (5.2.0+) |
70
- | `perClientBurst` | `number` (min 0) | `perClientPerSecond` floored at `1` | same | Burst capacity of the per-client bucket |
71
- | `identityHeader` | `string` | unset (socket IP) | unset | Trusted header supplying client identity (e.g. `x-forwarded-for`) |
66
+ | Key | Type | Default | Purpose |
67
+ | -------------------- | --------- | ------- | ----------------------------------------------------------------------- |
68
+ | `idleTimeoutSeconds` | `integer` | `1800` | TTL for idle session records in `system.mcp_session` |
69
+ | `allowClientDelete` | `boolean` | `false` | When `true`, accepts client-issued `DELETE /mcp` to terminate a session |
72
70
 
73
- `perClientPerSecond` (5.2.0+) survives session cycling. Only set `identityHeader` when a trusted proxy strips or replaces it on untrusted traffic — a client-controlled header bypasses per-client limits entirely.
71
+ 6. **Register a durable quota handler** (optional, `5.2.0+`): Call `server.setMcpQuotaHandler(handler)` in a component to enforce durable per-identity quotas that survive rate-limit bypasses (e.g. session cycling). The handler runs **after** in-memory buckets admit the call. Keep any backing table unexported (no `@export`) so it is invisible to all transports.
74
72
 
75
- 5. **Configure session lifecycle (`mcp.session.*`).** These settings apply to both profiles. A dropped session causes the next request bearing that session id to receive HTTP 404; the client is expected to re-`initialize`.
73
+ ```graphql
74
+ # schema.graphql — internal counter, no @export
75
+ type QuotaCounter @table {
76
+ id: ID @primaryKey
77
+ used: Int
78
+ }
79
+ ```
76
80
 
77
- | Key | Type | Default | Purpose |
78
- | -------------------- | ----------------- | ------- | ----------------------------------------------------------------------- |
79
- | `idleTimeoutSeconds` | `integer` (min 1) | `1800` | Idle window before a session is TTL-evicted from `system.mcp_session` |
80
- | `allowClientDelete` | `boolean` | `false` | When `true`, accepts client-issued `DELETE /mcp` to terminate a session |
81
+ ```javascript
82
+ // resources.js
83
+ const DAILY_LIMIT = 100;
81
84
 
82
- 6. **Register a durable quota handler (optional, 5.2.0+).** For cost control that survives restarts and session cycling, register a handler with `server.setMcpQuotaHandler`. The handler runs **after** in-memory buckets admit the call. Keep any backing table unexported (no `@export`). A handler that throws **denies** the call (fail-closed). The handler receives `{ identity, tool, user, profile, sessionId }` and must return `true` to allow or `{ allowed: false, message?, retryAfterSeconds? }` to deny.
85
+ export class Answerer extends Resource {
86
+ static mcpTools = [{ name: 'answer', description: 'Answer a question', method: 'doAnswer' }];
87
+ async doAnswer(args) {
88
+ return { answered: args?.q ?? '' };
89
+ }
90
+ }
91
+
92
+ server.setMcpQuotaHandler(async ({ identity, tool, user, profile, sessionId }) => {
93
+ if (profile !== 'application') return true;
94
+ const id = identity ?? 'unknown';
95
+ const existing = await tables.QuotaCounter.get(id);
96
+ const used = (existing?.used ?? 0) + 1;
97
+ await tables.QuotaCounter.put({ id, used });
98
+ if (used > DAILY_LIMIT) {
99
+ return { allowed: false, message: 'daily quota reached', retryAfterSeconds: 3600 };
100
+ }
101
+ return true;
102
+ });
103
+ ```
83
104
 
84
- 7. **Configure Origin validation for browser clients.** MCP validates the `Origin` header to defend against DNS-rebinding attacks. Validation reuses each profile's existing CORS config:
85
- - No `Origin` header (e.g. `curl`) → always accepted.
86
- - CORS disabled or `*` allow-list → any `Origin` accepted.
105
+ - Return `true` to allow; return `{ allowed: false, message?, retryAfterSeconds? }` to deny.
106
+ - Denials surface as `isError` tool result with `kind: 'quota_exceeded'`.
107
+ - **Fail-closed**: a handler that throws **denies** the call.
108
+ - Pass `undefined` to clear the handler. The latest registration wins.
109
+ - Race-safety (concurrent calls for the same identity) is the handler's responsibility.
110
+
111
+ 7. **Secure Origin validation**: The MCP endpoint validates the `Origin` header to defend against DNS-rebinding attacks. Rules:
112
+ - CORS disabled or `*` allow-list → any `Origin` is accepted.
87
113
  - CORS enabled with an explicit allow-list → `Origin` not in the list returns `403 Forbidden`.
114
+ - No `Origin` header (e.g. `curl` or server-to-server traffic) → always accepted.
115
+
116
+ Configure CORS on each profile's existing settings:
117
+ - Application profile: `http.cors` + `http.corsAccessList`
118
+ - Operations profile: `operationsApi.network.cors` + `operationsApi.network.corsAccessList`
88
119
 
89
- For browser-exposed deployments, enable CORS with an explicit (non-`*`) allow-list on the relevant profile.
120
+ Any deployment exposing MCP to browsers beyond loopback must enable CORS with an explicit (non-`*`) allow-list to activate Origin-based protection.
90
121
 
91
122
  #### Examples
92
123
 
93
- **Minimal — both profiles on with all defaults:**
124
+ **Minimal — both profiles on with defaults:**
94
125
 
95
126
  ```yaml
96
127
  mcp:
@@ -98,7 +129,7 @@ mcp:
98
129
  application: {}
99
130
  ```
100
131
 
101
- **Production deployment — locked-down operations profile, raised application throughput, graceful logout:**
132
+ **Full deployment example** — locked-down operations allow list, custom rate limits, raised application throughput, lower session-creation rate, extended session TTL, and client-initiated session deletion:
102
133
 
103
134
  ```yaml
104
135
  mcp:
@@ -116,54 +147,35 @@ mcp:
116
147
  rateLimit:
117
148
  perToolPerSecond: 50
118
149
  perToolBurst: 100
150
+ initializePerSecond: 2
151
+ initializeBurst: 20
119
152
  session:
120
153
  idleTimeoutSeconds: 3600
121
154
  allowClientDelete: true
122
155
  ```
123
156
 
124
- **Durable quota handler backed by an internal table:**
125
-
126
- ```graphql
127
- # schema.graphql — internal counter, no @export
128
- type QuotaCounter @table {
129
- id: ID @primaryKey
130
- used: Int
131
- }
132
- ```
133
-
134
- ```javascript
135
- // resources.js
136
- const DAILY_LIMIT = 100;
157
+ **Denied `initialize` response (HTTP 429):**
137
158
 
138
- export class Answerer extends Resource {
139
- static mcpTools = [{ name: 'answer', description: 'Answer a question', method: 'doAnswer' }];
140
- async doAnswer(args) {
141
- return { answered: args?.q ?? '' };
159
+ ```json
160
+ {
161
+ "jsonrpc": "2.0",
162
+ "id": 1,
163
+ "error": {
164
+ "code": -32600,
165
+ "message": "MCP initialize rate limit reached; back off and try again"
142
166
  }
143
167
  }
144
-
145
- server.setMcpQuotaHandler(async ({ identity, tool, user, profile, sessionId }) => {
146
- if (profile !== 'application') return true;
147
- const id = identity ?? 'unknown';
148
- const existing = await tables.QuotaCounter.get(id);
149
- const used = (existing?.used ?? 0) + 1;
150
- await tables.QuotaCounter.put({ id, used });
151
- if (used > DAILY_LIMIT) {
152
- return { allowed: false, message: 'daily quota reached', retryAfterSeconds: 3600 };
153
- }
154
- return true;
155
- });
156
168
  ```
157
169
 
158
170
  #### Notes
159
171
 
160
- - The `operations` profile mounts on port `9925`; the `application` profile mounts on port `9926`. These are the default ports — change `mountPath` only if `/mcp` collides with another route.
161
- - Setting `mcp.operations.allow` **replaces** the default list entirely. Do not add `get_*` as a glob — it exposes `get_configuration` (which can return TLS/S3/auth secrets) and other sensitive operations.
162
- - `perClientPerSecond` (5.2.0+) is disabled by default (`0`). Enable it to prevent session-cycling abuse.
163
- - The durable quota handler (5.2.0+) is fail-closed: a thrown error denies the call. Race-safety under concurrent workers is the handler's responsibility — use atomic read-modify-write for production counters.
164
- - Pass `undefined` to `server.setMcpQuotaHandler` to clear a registered handler. The latest registration wins on component reload.
165
- - Version notes: the transport and tool surface shipped across 5.1.x (complete protocol surface — prompts, resources, subscriptions, completions, cancellation, progress — in 5.1.10+). Custom content resources (`mcpResources`) are 5.1.18+. Per-client rate limiting (`perClientPerSecond`, `perClientBurst`, `identityHeader`) and the durable quota handler (`server.setMcpQuotaHandler`) are 5.2.0+. **Verify the version before relying on gated features.** Unsupported config keys (such as the `rateLimit.perClient*` security controls) are **accepted and silently ignored** by older versions — nothing errors, the feature just doesn't run. After a session is evicted, the client must re-`initialize` to establish a new session.
166
- - See [connecting-clients.md](connecting-clients.md) for how to connect MCP clients to these endpoints.
172
+ - Both profiles accept any `Origin` out of the box; tighten CORS before exposing MCP endpoints to browsers.
173
+ - `mcp.operations` serves on port `9925`; `mcp.application` serves on port `9926`.
174
+ - Numeric rate-limit values accept quoted strings (`"0.5"`) as well as plain numbers in `harper-config.yaml`.
175
+ - In-memory rate-limit state is per-worker and does not survive restarts; use `server.setMcpQuotaHandler(handler)` for durable quotas.
176
+ - The `allow` list for `mcp.operations` is shared with the built-in agent when `agent.enabled` is on — widening it also widens what the agent can call autonomously.
177
+ - To exclude a Resource from the MCP surface entirely, set `exportTypes.mcp = false` in its registration.
178
+ - See [connecting-clients.md](connecting-clients.md) for configuring MCP host clients to connect to these endpoints.
167
179
  - See [rate-limiting.md](rate-limiting.md) for broader rate-limiting context.
168
180
 
169
181
  ### 1.2 Connecting Clients
@@ -271,11 +283,11 @@ Instructions for the agent to follow when exposing custom instance methods as MC
271
283
 
272
284
  #### When to Use
273
285
 
274
- Apply this rule when a component needs to expose non-verb instance methods as callable MCP tools. Use it whenever you need custom business logic (e.g., reconciliation, aggregation, batch operations) accessible via the MCP transport beyond the auto-generated verb tools.
286
+ Apply this rule when a component needs to expose non-verb instance methods as callable MCP tools. Use it whenever you need to add custom business logic (e.g., reconciliation, aggregation, side-effecting operations) to the MCP tool surface beyond the auto-generated verb tools.
275
287
 
276
288
  #### How It Works
277
289
 
278
- 1. **Declare a static `mcpTools` array** on the Resource class. Each entry names the tool, maps it to an instance method, provides a description, and defines an `inputSchema`.
290
+ 1. **Declare `mcpTools` on the Resource class**: Add a static `mcpTools` array to your Resource subclass. Each entry names the tool, maps it to an instance method, provides a description, and defines an `inputSchema`.
279
291
 
280
292
  ```javascript
281
293
  class Orders extends Tables.orders {
@@ -297,39 +309,37 @@ Apply this rule when a component needs to expose non-verb instance methods as ca
297
309
  }
298
310
  ```
299
311
 
300
- 2. **Understand the security model.** Custom tools are exposed to **every** MCP session — including `anonymous`, unauthenticated ones. The MCP layer does **not**:
301
- - Run an `allow*` gate automatically.
302
- - Open a Resource transaction automatically.
303
- - Filter the tool from `tools/list` based on user role.
312
+ 2. **Understand the security model — no automatic auth**: The MCP transport audits the `tools/call` but invokes the custom instance method directly. It does **not** open a Resource transaction or run an `allow*` gate automatically. Custom tools are exposed to any MCP session — including `anonymous`, unauthenticated ones. The tool is listed to every session and its method executes even when no user is logged in (`context.user` may be empty).
304
313
 
305
- Unlike auto-generated verb tools (which are RBAC-filtered per user at `tools/list` time and enforce table permissions on call), a custom tool is listed to every session and its method executes even when no user is logged in. `context.user` may be empty.
306
-
307
- 3. **Enforce access control inside the method.** Because the MCP layer performs no authentication or ACL check, the method itself is fully responsible. Check `context.user` at the top of the method and throw when the caller doesn't qualify:
314
+ 3. **Enforce access control inside the method**: Because no `allow*` gate runs automatically, access control is entirely the method's responsibility. Check `context.user` inside the method and throw when the caller doesn't qualify.
308
315
 
309
316
  ```javascript
310
317
  async reconcileUnsettled({ since }) {
311
- if (!context.user || !context.user.roles.includes('admin')) {
312
- throw new Error('Unauthorized');
313
- }
318
+ if (!context.user?.id) throw new Error('Authentication required');
319
+ // role check example:
320
+ if (!context.user.roles?.includes('finance')) throw new Error('Forbidden');
314
321
  /* ... */
315
322
  }
316
323
  ```
317
324
 
318
- 4. **Delegate to static Resource operations correctly.** The MCP-created instance context carries the authenticated user and a one-shot `authorize` flag:
319
- - For the **first** delegated operation, pass `this.getContext()` directly — the `authorize` flag is consumed by that call:
320
- ```javascript
321
- const result = await Orders.get(target, this.getContext());
322
- ```
323
- - For **every subsequent** delegated operation, create a fresh `RequestTarget`, set `target.checkPermission = true` so authorization derives from `context.user`, and pass `this.getContext()`:
324
- ```javascript
325
- target.checkPermission = true;
326
- const next = await Orders.get(target, this.getContext());
327
- ```
328
- - **Never** accept `checkPermission` from tool arguments or other client input.
325
+ 4. **Pass an armed context when delegating to static Resource operations**: The MCP-created instance context carries the authenticated user and a one-shot `authorize` flag. Use `this.getContext()` for the first delegated call:
326
+
327
+ ```javascript
328
+ const result = await Orders.get(target, this.getContext());
329
+ ```
330
+
331
+ For every subsequent delegated operation, set `target.checkPermission = true` on a `RequestTarget` so authorization derives from `context.user`, and pass `this.getContext()`:
332
+
333
+ ```javascript
334
+ target.checkPermission = true;
335
+ const next = await Orders.get(target, this.getContext());
336
+ ```
337
+
338
+ 5. **Never accept `checkPermission` from tool arguments or client input**: Always set `target.checkPermission` in server-side code only. Do not read it from the tool's input arguments or any other client-supplied data.
329
339
 
330
340
  #### Examples
331
341
 
332
- Full class with a custom MCP tool that guards access via `context.user`:
342
+ Full class with a custom MCP tool that enforces authentication and delegates with proper context:
333
343
 
334
344
  ```javascript
335
345
  class Orders extends Tables.orders {
@@ -346,30 +356,26 @@ class Orders extends Tables.orders {
346
356
  ];
347
357
 
348
358
  async reconcileUnsettled({ since }) {
349
- // Reject anonymous or unauthorized callers — the MCP layer does not do this.
350
- if (!context.user) {
351
- throw new Error('Authentication required');
352
- }
359
+ // Enforce auth — context.user may be empty for anonymous sessions
360
+ if (!context.user?.id) throw new Error('Authentication required');
353
361
 
354
- // First delegated operation: use the one-shot authorize flag via this.getContext().
355
- const target = { since };
362
+ // First delegated operation uses the one-shot authorize flag
363
+ const target = { checkPermission: true, since };
356
364
  const unsettled = await Orders.get(target, this.getContext());
357
365
 
358
- // Subsequent delegated operations: fresh RequestTarget with checkPermission = true.
359
- const updateTarget = { id: unsettled.id };
360
- updateTarget.checkPermission = true;
361
- await Orders.update(updateTarget, this.getContext());
366
+ // Subsequent delegated operations set checkPermission server-side
367
+ target.checkPermission = true;
368
+ // ... further operations
362
369
  }
363
370
  }
364
371
  ```
365
372
 
366
373
  #### Notes
367
374
 
368
- - `mcpTools` is a **static** array — declare it on the class, not on instances.
369
- - The `allow*` gates that protect auto-generated verb tools do **not** run for custom tools. All authorization logic must live inside the method.
370
- - `context.user` is the canonical way to identify the caller; it may be empty for `anonymous` sessions, so always check before trusting it.
371
- - Never derive `checkPermission` from client-supplied tool arguments — always set it explicitly in your method code.
372
- - If your custom tool performs expensive or repeated operations, consider applying [rate limiting](rate-limiting.md) or [durable quotas](durable-quotas.md) inside the method to prevent abuse by unauthenticated callers.
375
+ - Unlike auto-generated verb tools, which are RBAC-filtered per user at `tools/list` time and enforce table permissions on call, custom `mcpTools` entries bypass all of that — the method runs for any caller, including `anonymous` sessions.
376
+ - The `allow*` gates that protect standard verb operations do not apply to custom tools. All authorization logic must live inside the method itself, using `context.user`.
377
+ - The one-shot `authorize` flag on the MCP-created context is consumed by the first static Resource operation. Set `target.checkPermission = true` for every subsequent call.
378
+ - Consider applying [rate-limiting](rate-limiting.md) and [durable-quotas](durable-quotas.md) to custom tools that perform expensive or side-effecting operations, since no built-in throttling is applied automatically.
373
379
 
374
380
  ### 2.3 Custom MCP Prompts
375
381
 
@@ -517,56 +523,123 @@ Public docs server: the two-entry declaration above plus `mcp.application.mountP
517
523
 
518
524
  ## 4. Operations & Security
519
525
 
520
- ### 4.1 Rate Limiting
526
+ ### 4.1 Rate Limiting MCP Tool Calls
521
527
 
522
- In-memory token buckets that bound `tools/call` throughput per profile.
528
+ Instructions for the agent to follow when configuring per-tool, per-session, and per-client-identity token-bucket rate limits on Harper MCP profiles.
523
529
 
524
530
  #### When to Use
525
531
 
526
- Use this skill when tuning MCP throughput, and **always** when a tool is exposed on a public or anonymous-accessible instance — the default limits alone do not stop session-cycling abuse.
532
+ Apply this rule when configuring `mcp.<profile>.rateLimit.*` keys to throttle `tools/call` invocations. Use it when you need to protect a worker from runaway sessions, prevent session-cycling abuse via per-client buckets, or control the rate of session creation via `initialize` limits.
527
533
 
528
534
  #### How It Works
529
535
 
530
- Four session-scoped limits ship with sensible defaults (per profile, configurable under `mcp.<profile>.rateLimit.*`):
536
+ 1. **Understand the bucket model**: Harper maintains two token buckets per `tools/call` invocation — one per `(session, tool)` pair and one per session across all tools. When either bucket is exhausted, `tools/call` returns `result.isError = true` with `kind: "rate_limited"` (not a JSON-RPC error), so the LLM can read the message and back off without tearing down the transport.
531
537
 
532
- - `perToolPerSecond` / `perToolBurst` — sustained rate and burst per (session, tool).
533
- - `sessionConcurrency` — max in-flight calls per session.
534
- - `sessionPerSecond` — sustained rate per session across all tools.
538
+ 2. **Set per-tool sustained rate and burst**: Configure how fast the per-tool bucket refills and how many back-to-back calls a single tool can absorb.
535
539
 
536
- Limit hits return an `isError` tool result with `kind: 'rate_limited'` and a `scope` field (not a JSON-RPC error), so the calling LLM can see and back off.
540
+ ```yaml
541
+ mcp.<profile>.rateLimit.perToolPerSecond: 10
542
+ mcp.<profile>.rateLimit.perToolBurst: 20
543
+ ```
537
544
 
538
- **Session buckets are evadable by anonymous clients**: `initialize → call → drop session → repeat` gets fresh buckets every loop. Two additions close that (5.2.0+):
545
+ Set `perToolPerSecond` to `0` to disable per-tool throttling. Every numeric key accepts a quoted number (`"0.5"`) or a plain number.
539
546
 
540
- - `perClientPerSecond` / `perClientBurst` (default off) — a bucket keyed on **client identity** rather than session, surviving the cycling loop. Burst defaults to the sustained rate, floored at one whole token (a fractional rate like `0.1` = "6/minute" still admits its first call). Denials report `scope: 'per_client'`.
541
- - `identityHeader` — identity defaults to the client socket IP; deployments behind a reverse proxy can name a trusted header (typically `x-forwarded-for`, first value wins). **Only set this when the proxy strips or replaces the header on untrusted traffic** — a client-controlled identity header lets callers mint fresh identities per request and bypass the limit; Harper logs a startup warning when it is configured.
547
+ 3. **Set per-session concurrency and sustained rate**: Limit how many `tools/call` invocations a session may have in flight at once, and cap the aggregate rate across all tools in that session.
542
548
 
543
- All bucket state is in-memory per worker: it resets on restart and is not shared across workers. For durable, restart-surviving limits, see the [Durable Quotas](durable-quotas.md) skill.
549
+ ```yaml
550
+ mcp.<profile>.rateLimit.sessionConcurrency: 25
551
+ mcp.<profile>.rateLimit.sessionPerSecond: 100
552
+ ```
553
+
554
+ Exceeding `sessionConcurrency` returns `kind: "rate_limited"` with `scope: "concurrency"`. `sessionPerSecond` catches sessions that spread calls across many distinct tools to dodge `perTool*` limits.
555
+
556
+ 4. **Enable per-client identity buckets with `perClientPerSecond`**: Session-scoped buckets can be evaded by a client that cycles sessions (`initialize` → call → drop → repeat). The client bucket survives that loop.
557
+
558
+ ```yaml
559
+ mcp.<profile>.rateLimit.perClientPerSecond: 10
560
+ mcp.<profile>.rateLimit.perClientBurst: 10
561
+ ```
562
+
563
+ Denials surface as an `isError` tool result with `kind: 'rate_limited'`, `scope: 'per_client'`. `perClientPerSecond` defaults to `0` (disabled). `perClientBurst` defaults to the `perClientPerSecond` value floored at `1` — a fractional rate like `0.1` (6 per minute) still yields `perClientBurst: 1` so the bucket can admit at least one call.
564
+
565
+ 5. **Control session creation rate with `initializePerSecond`**: Unlike `perClientPerSecond`, this limit is **on by default** (`10`). A denied `initialize` returns HTTP `429` with a `Retry-After` header — not a tool result with `kind: "rate_limited"`.
566
+
567
+ ```yaml
568
+ mcp.<profile>.rateLimit.initializePerSecond: 10
569
+ mcp.<profile>.rateLimit.initializeBurst: 50
570
+ ```
544
571
 
545
- On Harper versions before 5.2.0 the `perClient*`/`identityHeader` keys are **accepted and silently ignored** — verify `serverInfo.version` and prove a denial once before trusting the limit (see [Enabling MCP](enabling-mcp.md)).
572
+ `Retry-After` is `ceil(1 / initializePerSecond)` seconds. Set `initializePerSecond` to `0` to disable. The denied response body is:
573
+
574
+ ```json
575
+ {
576
+ "jsonrpc": "2.0",
577
+ "id": 1,
578
+ "error": {
579
+ "code": -32600,
580
+ "message": "MCP initialize rate limit reached; back off and try again"
581
+ }
582
+ }
583
+ ```
584
+
585
+ 6. **Configure `identityHeader` for reverse-proxy deployments**: When every socket IP is the proxy's IP, set `identityHeader` to the name of a trusted header whose first (client-most) value supplies the real client identity. Typically `x-forwarded-for`.
586
+
587
+ ```yaml
588
+ mcp.<profile>.rateLimit.identityHeader: 'x-forwarded-for'
589
+ ```
590
+
591
+ **Only set this when the fronting proxy strips or replaces the header on untrusted traffic.** A client-controlled identity header lets callers mint fresh identities per request and bypass per-client limits entirely. Harper logs a startup warning when this key is configured.
592
+
593
+ Harper canonicalizes the identity before counting:
594
+ - An IPv4 address with a port, and an IPv4-mapped IPv6 address (`::ffff:192.0.2.1`), count as the plain IPv4 address.
595
+ - Any other IPv6 address counts as its `/64`.
596
+ - A request with no identity shares one bucket per profile instead of going unthrottled.
597
+ - Past 100,000 tracked identities per profile and worker, new identities also share that bucket.
598
+
599
+ 7. **Understand in-memory state limits**: All bucket state is in-memory per worker. It does not survive a restart and is not shared across workers. For durable quotas that persist across restarts and workers, see [durable-quotas.md](durable-quotas.md).
546
600
 
547
601
  #### Examples
548
602
 
549
- Public docs server with a cost-bearing `answer` tool — bound instantaneous abuse:
603
+ Full rate-limit configuration for a profile:
550
604
 
551
605
  ```yaml
552
- mcp:
553
- application:
554
- mountPath: /mcp
555
- rateLimit:
556
- perClientPerSecond: 0.5 # 30/minute sustained per client
557
- perClientBurst: 5
606
+ mcp.operations.rateLimit.perToolPerSecond: 10
607
+ mcp.operations.rateLimit.perToolBurst: 20
608
+ mcp.operations.rateLimit.sessionConcurrency: 25
609
+ mcp.operations.rateLimit.sessionPerSecond: 100
610
+ mcp.operations.rateLimit.perClientPerSecond: 5
611
+ mcp.operations.rateLimit.perClientBurst: 10
612
+ mcp.operations.rateLimit.initializePerSecond: 10
613
+ mcp.operations.rateLimit.initializeBurst: 50
614
+ mcp.operations.rateLimit.identityHeader: 'x-forwarded-for'
558
615
  ```
559
616
 
560
- Behind a proxy that manages `X-Forwarded-For` correctly:
617
+ Fractional per-client rate (6 calls per minute) with default burst:
561
618
 
562
619
  ```yaml
563
- mcp:
564
- application:
565
- rateLimit:
566
- identityHeader: x-forwarded-for
567
- perClientPerSecond: 0.5
620
+ mcp.application.rateLimit.perClientPerSecond: '0.1'
621
+ # perClientBurst defaults to 1 (floored from 0.1)
568
622
  ```
569
623
 
624
+ #### Notes
625
+
626
+ | Key | Type | Default (operations / application) |
627
+ | --------------------- | --------------- | ----------------------------------- |
628
+ | `perToolPerSecond` | number (min 0) | `10` / `25` |
629
+ | `perToolBurst` | number (min 0) | `20` / `50` |
630
+ | `sessionConcurrency` | integer (min 0) | `25` / `50` |
631
+ | `sessionPerSecond` | number (min 0) | `100` / `200` |
632
+ | `perClientPerSecond` | number (min 0) | `0` (disabled) |
633
+ | `perClientBurst` | number (min 0) | `perClientPerSecond` floored at `1` |
634
+ | `initializePerSecond` | number (min 0) | `10` |
635
+ | `initializeBurst` | number (min 1) | `50` |
636
+ | `identityHeader` | string | unset (socket IP) |
637
+
638
+ - The `initialize` limit is the only one that rejects with HTTP `429`; all other exhausted buckets return an `isError` tool result with `kind: "rate_limited"`.
639
+ - On the application profile, a client spreading connections across HTTP worker threads gets the configured rate and burst once per worker; a client reusing one connection stays on one worker.
640
+ - The operations profile is served by the main thread only, so it admits exactly the configured figure.
641
+ - For quotas that survive restarts and are shared across workers, see [durable-quotas.md](durable-quotas.md).
642
+
570
643
  ### 4.2 Durable Quotas
571
644
 
572
645
  Persisted, restart-surviving cost controls for `tools/call`, registered as a plain function in your component code (5.2.0+).