@harperfast/template-vue-studio 1.13.6 → 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
@@ -7,8 +7,8 @@ metadata:
7
7
  mode: generate
8
8
  sources:
9
9
  - reference/v5/mcp/tools-and-resources.md#Custom `mcpTools` opt-in
10
- sourceCommit: 9e6ecf87dd25bb488ad44dc2876ca6439ccd682e
11
- inputHash: 692801362e747c73
10
+ sourceCommit: da68d8e45f5422321c128a0cd67694bd0b97b155
11
+ inputHash: 9206d4f9fb192f88
12
12
  ---
13
13
 
14
14
  # Custom MCP Tools
@@ -17,11 +17,11 @@ Instructions for the agent to follow when exposing custom instance methods as MC
17
17
 
18
18
  ## When to Use
19
19
 
20
- 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.
20
+ 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.
21
21
 
22
22
  ## How It Works
23
23
 
24
- 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`.
24
+ 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`.
25
25
 
26
26
  ```javascript
27
27
  class Orders extends Tables.orders {
@@ -43,39 +43,37 @@ Apply this rule when a component needs to expose non-verb instance methods as ca
43
43
  }
44
44
  ```
45
45
 
46
- 2. **Understand the security model.** Custom tools are exposed to **every** MCP session — including `anonymous`, unauthenticated ones. The MCP layer does **not**:
47
- - Run an `allow*` gate automatically.
48
- - Open a Resource transaction automatically.
49
- - Filter the tool from `tools/list` based on user role.
46
+ 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).
50
47
 
51
- 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.
52
-
53
- 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:
48
+ 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.
54
49
 
55
50
  ```javascript
56
51
  async reconcileUnsettled({ since }) {
57
- if (!context.user || !context.user.roles.includes('admin')) {
58
- throw new Error('Unauthorized');
59
- }
52
+ if (!context.user?.id) throw new Error('Authentication required');
53
+ // role check example:
54
+ if (!context.user.roles?.includes('finance')) throw new Error('Forbidden');
60
55
  /* ... */
61
56
  }
62
57
  ```
63
58
 
64
- 4. **Delegate to static Resource operations correctly.** The MCP-created instance context carries the authenticated user and a one-shot `authorize` flag:
65
- - For the **first** delegated operation, pass `this.getContext()` directly — the `authorize` flag is consumed by that call:
66
- ```javascript
67
- const result = await Orders.get(target, this.getContext());
68
- ```
69
- - For **every subsequent** delegated operation, create a fresh `RequestTarget`, set `target.checkPermission = true` so authorization derives from `context.user`, and pass `this.getContext()`:
70
- ```javascript
71
- target.checkPermission = true;
72
- const next = await Orders.get(target, this.getContext());
73
- ```
74
- - **Never** accept `checkPermission` from tool arguments or other client input.
59
+ 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:
60
+
61
+ ```javascript
62
+ const result = await Orders.get(target, this.getContext());
63
+ ```
64
+
65
+ For every subsequent delegated operation, set `target.checkPermission = true` on a `RequestTarget` so authorization derives from `context.user`, and pass `this.getContext()`:
66
+
67
+ ```javascript
68
+ target.checkPermission = true;
69
+ const next = await Orders.get(target, this.getContext());
70
+ ```
71
+
72
+ 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.
75
73
 
76
74
  ## Examples
77
75
 
78
- Full class with a custom MCP tool that guards access via `context.user`:
76
+ Full class with a custom MCP tool that enforces authentication and delegates with proper context:
79
77
 
80
78
  ```javascript
81
79
  class Orders extends Tables.orders {
@@ -92,27 +90,23 @@ class Orders extends Tables.orders {
92
90
  ];
93
91
 
94
92
  async reconcileUnsettled({ since }) {
95
- // Reject anonymous or unauthorized callers — the MCP layer does not do this.
96
- if (!context.user) {
97
- throw new Error('Authentication required');
98
- }
93
+ // Enforce auth — context.user may be empty for anonymous sessions
94
+ if (!context.user?.id) throw new Error('Authentication required');
99
95
 
100
- // First delegated operation: use the one-shot authorize flag via this.getContext().
101
- const target = { since };
96
+ // First delegated operation uses the one-shot authorize flag
97
+ const target = { checkPermission: true, since };
102
98
  const unsettled = await Orders.get(target, this.getContext());
103
99
 
104
- // Subsequent delegated operations: fresh RequestTarget with checkPermission = true.
105
- const updateTarget = { id: unsettled.id };
106
- updateTarget.checkPermission = true;
107
- await Orders.update(updateTarget, this.getContext());
100
+ // Subsequent delegated operations set checkPermission server-side
101
+ target.checkPermission = true;
102
+ // ... further operations
108
103
  }
109
104
  }
110
105
  ```
111
106
 
112
107
  ## Notes
113
108
 
114
- - `mcpTools` is a **static** array — declare it on the class, not on instances.
115
- - The `allow*` gates that protect auto-generated verb tools do **not** run for custom tools. All authorization logic must live inside the method.
116
- - `context.user` is the canonical way to identify the caller; it may be empty for `anonymous` sessions, so always check before trusting it.
117
- - Never derive `checkPermission` from client-supplied tool arguments — always set it explicitly in your method code.
118
- - 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.
109
+ - 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.
110
+ - 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`.
111
+ - 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.
112
+ - 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.
@@ -8,21 +8,21 @@ metadata:
8
8
  sources:
9
9
  - reference/v5/mcp/overview.md
10
10
  - reference/v5/mcp/configuration.md
11
- sourceCommit: 2cfb81318f17e0aca2d600109e6ad813d2d0443e
12
- inputHash: 53ecfa7dd46bed75
11
+ sourceCommit: 179def6d5df976cf0a6b2bec24908ecfde993c22
12
+ inputHash: 0268d6ede5741225
13
13
  ---
14
14
 
15
15
  # Enabling and Configuring Harper MCP Server Profiles
16
16
 
17
- Instructions for the agent to enable and configure Harper's MCP server profiles (`operations` and `application`) using the `mcp:` block in `harper-config.yaml`.
17
+ Instructions for the agent to enable and configure Harper's MCP server profiles (`operations` and `application`) in `harper-config.yaml`.
18
18
 
19
19
  ## When to Use
20
20
 
21
- 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.
21
+ 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.
22
22
 
23
23
  ## How It Works
24
24
 
25
- 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:
25
+ 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:
26
26
 
27
27
  ```yaml
28
28
  mcp:
@@ -30,75 +30,106 @@ Apply this rule when adding MCP support to a Harper deployment so that LLM hosts
30
30
  application: {}
31
31
  ```
32
32
 
33
- - The `operations` profile mounts at `/mcp` on the **operations server** (default port `9925`).
34
- - The `application` profile mounts at `/mcp` on the **application HTTP server** (default port `9926`).
33
+ - `operations` mounts at `/mcp` on the **operations server** (default port `9925`).
34
+ - `application` mounts at `/mcp` on the **application HTTP server** (default port `9926`).
35
35
 
36
- 2. **Configure the operations profile (`mcp.operations`).** This profile wraps Harper's operation catalog.
36
+ 2. **Configure the operations profile** (`mcp.operations.*`): Control which operations are exposed as MCP tools.
37
37
 
38
- | Key | Type | Default | Purpose |
39
- | ----------- | ----------------- | --------- | -------------------------------------------------------------------------------- |
40
- | `mountPath` | `string` | `/mcp` | URL path the endpoint mounts on |
41
- | `allow` | `array<string>` | See below | Operations exposed as MCP tools (glob or literal); **replaces** the default list |
42
- | `deny` | `array<string>` | `[]` | Operations filtered out after `allow` is applied |
43
- | `maxTools` | `integer` (min 1) | `200` | Max tools per `tools/list` response page |
38
+ | Key | Type | Default | Purpose |
39
+ | ----------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
40
+ | `mountPath` | `string` | `/mcp` | URL path for the endpoint |
41
+ | `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 |
42
+ | `deny` | `array<string>` | `[]` | Operations filtered out after `allow` is applied |
43
+ | `maxTools` | `integer` | `200` | Max tools per `tools/list` page |
44
44
 
45
- Default `allow` list:
45
+ 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.
46
46
 
47
- ```yaml
48
- allow:
49
- - describe_*
50
- - list_*
51
- - search_*
52
- - get_job
53
- - get_status
54
- - get_analytics
55
- - get_metrics
56
- - system_information
57
- - read_log
58
- - read_audit_log
59
- ```
47
+ 3. **Configure the application profile** (`mcp.application.*`): Controls the endpoint that walks your exported `Resource` classes.
48
+
49
+ | Key | Type | Default | Purpose |
50
+ | ------------------ | --------- | ------- | ------------------------------------------------------------------ |
51
+ | `searchMaxResults` | `integer` | `1000` | Hard cap on records a `search_<resource>` tool can return per call |
60
52
 
61
- Setting `allow` **replaces** the default — it does not merge. To expose destructive operations (e.g. `set_configuration`, `drop_table`), add them explicitly.
53
+ 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.
62
54
 
63
- 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:
55
+ 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.
64
56
 
65
- | Key | Type | Default | Purpose |
66
- | ------------------ | ----------------- | ------- | ------------------------------------------------------------------ |
67
- | `searchMaxResults` | `integer` (min 1) | `1000` | Hard cap on records a `search_<resource>` tool can return per call |
57
+ | Key | Type | Default (operations / application) | Purpose |
58
+ | --------------------- | --------- | ----------------------------------- | ----------------------------------------------------------------- |
59
+ | `perToolPerSecond` | `number` | `10` / `25` | Sustained per-tool refill rate; `0` disables |
60
+ | `perToolBurst` | `number` | `20` / `50` | Burst capacity of the per-tool bucket |
61
+ | `sessionConcurrency` | `integer` | `25` / `50` | Max concurrent `tools/call` per session |
62
+ | `sessionPerSecond` | `number` | `100` / `200` | Sustained per-session rate across all tools |
63
+ | `perClientPerSecond` | `number` | `0` (disabled) | Sustained rate keyed on client identity (5.2.0+) |
64
+ | `perClientBurst` | `number` | `perClientPerSecond` floored at `1` | Burst capacity of the per-client bucket |
65
+ | `initializePerSecond` | `number` | `10` | Sustained session-creation rate per client identity; `0` disables |
66
+ | `initializeBurst` | `number` | `50` | Burst capacity of the `initialize` bucket |
67
+ | `identityHeader` | `string` | unset (socket IP) | Trusted header supplying client identity (e.g. `x-forwarded-for`) |
68
+ - `perClientPerSecond` survives session cycling — it is keyed on client identity, not session (5.2.0+).
69
+ - `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.
70
+ - Only set `identityHeader` when the fronting proxy strips or replaces it on untrusted traffic.
68
71
 
69
- 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.
72
+ 5. **Configure session lifecycle** (`mcp.session.*`):
70
73
 
71
- | Key | Type | Default (operations) | Default (application) | Purpose |
72
- | -------------------- | ----------------- | ----------------------------------- | --------------------- | ----------------------------------------------------------------- |
73
- | `perToolPerSecond` | `number` (min 0) | `10` | `25` | Sustained per-tool refill rate; `0` disables |
74
- | `perToolBurst` | `number` (min 0) | `20` | `50` | Burst capacity of the per-tool bucket |
75
- | `sessionConcurrency` | `integer` (min 0) | `25` | `50` | Max concurrent `tools/call` per session |
76
- | `sessionPerSecond` | `number` (min 0) | `100` | `200` | Sustained per-session rate across all tools |
77
- | `perClientPerSecond` | `number` (min 0) | `0` (disabled) | `0` (disabled) | Sustained rate keyed on client identity (5.2.0+) |
78
- | `perClientBurst` | `number` (min 0) | `perClientPerSecond` floored at `1` | same | Burst capacity of the per-client bucket |
79
- | `identityHeader` | `string` | unset (socket IP) | unset | Trusted header supplying client identity (e.g. `x-forwarded-for`) |
74
+ | Key | Type | Default | Purpose |
75
+ | -------------------- | --------- | ------- | ----------------------------------------------------------------------- |
76
+ | `idleTimeoutSeconds` | `integer` | `1800` | TTL for idle session records in `system.mcp_session` |
77
+ | `allowClientDelete` | `boolean` | `false` | When `true`, accepts client-issued `DELETE /mcp` to terminate a session |
80
78
 
81
- `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.
79
+ 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.
82
80
 
83
- 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`.
81
+ ```graphql
82
+ # schema.graphql — internal counter, no @export
83
+ type QuotaCounter @table {
84
+ id: ID @primaryKey
85
+ used: Int
86
+ }
87
+ ```
84
88
 
85
- | Key | Type | Default | Purpose |
86
- | -------------------- | ----------------- | ------- | ----------------------------------------------------------------------- |
87
- | `idleTimeoutSeconds` | `integer` (min 1) | `1800` | Idle window before a session is TTL-evicted from `system.mcp_session` |
88
- | `allowClientDelete` | `boolean` | `false` | When `true`, accepts client-issued `DELETE /mcp` to terminate a session |
89
+ ```javascript
90
+ // resources.js
91
+ const DAILY_LIMIT = 100;
92
+
93
+ export class Answerer extends Resource {
94
+ static mcpTools = [{ name: 'answer', description: 'Answer a question', method: 'doAnswer' }];
95
+ async doAnswer(args) {
96
+ return { answered: args?.q ?? '' };
97
+ }
98
+ }
99
+
100
+ server.setMcpQuotaHandler(async ({ identity, tool, user, profile, sessionId }) => {
101
+ if (profile !== 'application') return true;
102
+ const id = identity ?? 'unknown';
103
+ const existing = await tables.QuotaCounter.get(id);
104
+ const used = (existing?.used ?? 0) + 1;
105
+ await tables.QuotaCounter.put({ id, used });
106
+ if (used > DAILY_LIMIT) {
107
+ return { allowed: false, message: 'daily quota reached', retryAfterSeconds: 3600 };
108
+ }
109
+ return true;
110
+ });
111
+ ```
89
112
 
90
- 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.
113
+ - Return `true` to allow; return `{ allowed: false, message?, retryAfterSeconds? }` to deny.
114
+ - Denials surface as `isError` tool result with `kind: 'quota_exceeded'`.
115
+ - **Fail-closed**: a handler that throws **denies** the call.
116
+ - Pass `undefined` to clear the handler. The latest registration wins.
117
+ - Race-safety (concurrent calls for the same identity) is the handler's responsibility.
91
118
 
92
- 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:
93
- - No `Origin` header (e.g. `curl`) → always accepted.
94
- - CORS disabled or `*` allow-list → any `Origin` accepted.
119
+ 7. **Secure Origin validation**: The MCP endpoint validates the `Origin` header to defend against DNS-rebinding attacks. Rules:
120
+ - CORS disabled or `*` allow-list → any `Origin` is accepted.
95
121
  - CORS enabled with an explicit allow-list → `Origin` not in the list returns `403 Forbidden`.
122
+ - No `Origin` header (e.g. `curl` or server-to-server traffic) → always accepted.
123
+
124
+ Configure CORS on each profile's existing settings:
125
+ - Application profile: `http.cors` + `http.corsAccessList`
126
+ - Operations profile: `operationsApi.network.cors` + `operationsApi.network.corsAccessList`
96
127
 
97
- For browser-exposed deployments, enable CORS with an explicit (non-`*`) allow-list on the relevant profile.
128
+ Any deployment exposing MCP to browsers beyond loopback must enable CORS with an explicit (non-`*`) allow-list to activate Origin-based protection.
98
129
 
99
130
  ## Examples
100
131
 
101
- **Minimal — both profiles on with all defaults:**
132
+ **Minimal — both profiles on with defaults:**
102
133
 
103
134
  ```yaml
104
135
  mcp:
@@ -106,7 +137,7 @@ mcp:
106
137
  application: {}
107
138
  ```
108
139
 
109
- **Production deployment — locked-down operations profile, raised application throughput, graceful logout:**
140
+ **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:
110
141
 
111
142
  ```yaml
112
143
  mcp:
@@ -124,52 +155,33 @@ mcp:
124
155
  rateLimit:
125
156
  perToolPerSecond: 50
126
157
  perToolBurst: 100
158
+ initializePerSecond: 2
159
+ initializeBurst: 20
127
160
  session:
128
161
  idleTimeoutSeconds: 3600
129
162
  allowClientDelete: true
130
163
  ```
131
164
 
132
- **Durable quota handler backed by an internal table:**
165
+ **Denied `initialize` response (HTTP 429):**
133
166
 
134
- ```graphql
135
- # schema.graphql — internal counter, no @export
136
- type QuotaCounter @table {
137
- id: ID @primaryKey
138
- used: Int
139
- }
140
- ```
141
-
142
- ```javascript
143
- // resources.js
144
- const DAILY_LIMIT = 100;
145
-
146
- export class Answerer extends Resource {
147
- static mcpTools = [{ name: 'answer', description: 'Answer a question', method: 'doAnswer' }];
148
- async doAnswer(args) {
149
- return { answered: args?.q ?? '' };
167
+ ```json
168
+ {
169
+ "jsonrpc": "2.0",
170
+ "id": 1,
171
+ "error": {
172
+ "code": -32600,
173
+ "message": "MCP initialize rate limit reached; back off and try again"
150
174
  }
151
175
  }
152
-
153
- server.setMcpQuotaHandler(async ({ identity, tool, user, profile, sessionId }) => {
154
- if (profile !== 'application') return true;
155
- const id = identity ?? 'unknown';
156
- const existing = await tables.QuotaCounter.get(id);
157
- const used = (existing?.used ?? 0) + 1;
158
- await tables.QuotaCounter.put({ id, used });
159
- if (used > DAILY_LIMIT) {
160
- return { allowed: false, message: 'daily quota reached', retryAfterSeconds: 3600 };
161
- }
162
- return true;
163
- });
164
176
  ```
165
177
 
166
178
  ## Notes
167
179
 
168
- - 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.
169
- - 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.
170
- - `perClientPerSecond` (5.2.0+) is disabled by default (`0`). Enable it to prevent session-cycling abuse.
171
- - 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.
172
- - Pass `undefined` to `server.setMcpQuotaHandler` to clear a registered handler. The latest registration wins on component reload.
173
- - 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.
174
- - See [connecting-clients.md](connecting-clients.md) for how to connect MCP clients to these endpoints.
180
+ - Both profiles accept any `Origin` out of the box; tighten CORS before exposing MCP endpoints to browsers.
181
+ - `mcp.operations` serves on port `9925`; `mcp.application` serves on port `9926`.
182
+ - Numeric rate-limit values accept quoted strings (`"0.5"`) as well as plain numbers in `harper-config.yaml`.
183
+ - In-memory rate-limit state is per-worker and does not survive restarts; use `server.setMcpQuotaHandler(handler)` for durable quotas.
184
+ - 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.
185
+ - To exclude a Resource from the MCP surface entirely, set `exportTypes.mcp = false` in its registration.
186
+ - See [connecting-clients.md](connecting-clients.md) for configuring MCP host clients to connect to these endpoints.
175
187
  - See [rate-limiting.md](rate-limiting.md) for broader rate-limiting context.
@@ -7,56 +7,123 @@ metadata:
7
7
  mode: generate
8
8
  sources:
9
9
  - reference/v5/mcp/configuration.md#`mcp.<profile>.rateLimit.*`
10
- sourceCommit: d7d2ddb120ce5f2ad39dc425f628f5a4f220c151
11
- inputHash: c07b006ea6def652
10
+ sourceCommit: d999e45c73736c9e96d91eb839b6176db0bf1f51
11
+ inputHash: e25db2f26820723f
12
12
  ---
13
13
 
14
- # Rate Limiting
14
+ # Rate Limiting MCP Tool Calls
15
15
 
16
- In-memory token buckets that bound `tools/call` throughput per profile.
16
+ Instructions for the agent to follow when configuring per-tool, per-session, and per-client-identity token-bucket rate limits on Harper MCP profiles.
17
17
 
18
18
  ## When to Use
19
19
 
20
- 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.
20
+ 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.
21
21
 
22
22
  ## How It Works
23
23
 
24
- Four session-scoped limits ship with sensible defaults (per profile, configurable under `mcp.<profile>.rateLimit.*`):
24
+ 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.
25
25
 
26
- - `perToolPerSecond` / `perToolBurst` — sustained rate and burst per (session, tool).
27
- - `sessionConcurrency` — max in-flight calls per session.
28
- - `sessionPerSecond` — sustained rate per session across all tools.
26
+ 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.
29
27
 
30
- 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.
28
+ ```yaml
29
+ mcp.<profile>.rateLimit.perToolPerSecond: 10
30
+ mcp.<profile>.rateLimit.perToolBurst: 20
31
+ ```
31
32
 
32
- **Session buckets are evadable by anonymous clients**: `initialize → call → drop session → repeat` gets fresh buckets every loop. Two additions close that (5.2.0+):
33
+ Set `perToolPerSecond` to `0` to disable per-tool throttling. Every numeric key accepts a quoted number (`"0.5"`) or a plain number.
33
34
 
34
- - `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'`.
35
- - `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.
35
+ 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.
36
36
 
37
- 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.
37
+ ```yaml
38
+ mcp.<profile>.rateLimit.sessionConcurrency: 25
39
+ mcp.<profile>.rateLimit.sessionPerSecond: 100
40
+ ```
38
41
 
39
- 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)).
42
+ Exceeding `sessionConcurrency` returns `kind: "rate_limited"` with `scope: "concurrency"`. `sessionPerSecond` catches sessions that spread calls across many distinct tools to dodge `perTool*` limits.
43
+
44
+ 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.
45
+
46
+ ```yaml
47
+ mcp.<profile>.rateLimit.perClientPerSecond: 10
48
+ mcp.<profile>.rateLimit.perClientBurst: 10
49
+ ```
50
+
51
+ 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.
52
+
53
+ 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"`.
54
+
55
+ ```yaml
56
+ mcp.<profile>.rateLimit.initializePerSecond: 10
57
+ mcp.<profile>.rateLimit.initializeBurst: 50
58
+ ```
59
+
60
+ `Retry-After` is `ceil(1 / initializePerSecond)` seconds. Set `initializePerSecond` to `0` to disable. The denied response body is:
61
+
62
+ ```json
63
+ {
64
+ "jsonrpc": "2.0",
65
+ "id": 1,
66
+ "error": {
67
+ "code": -32600,
68
+ "message": "MCP initialize rate limit reached; back off and try again"
69
+ }
70
+ }
71
+ ```
72
+
73
+ 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`.
74
+
75
+ ```yaml
76
+ mcp.<profile>.rateLimit.identityHeader: 'x-forwarded-for'
77
+ ```
78
+
79
+ **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.
80
+
81
+ Harper canonicalizes the identity before counting:
82
+ - An IPv4 address with a port, and an IPv4-mapped IPv6 address (`::ffff:192.0.2.1`), count as the plain IPv4 address.
83
+ - Any other IPv6 address counts as its `/64`.
84
+ - A request with no identity shares one bucket per profile instead of going unthrottled.
85
+ - Past 100,000 tracked identities per profile and worker, new identities also share that bucket.
86
+
87
+ 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).
40
88
 
41
89
  ## Examples
42
90
 
43
- Public docs server with a cost-bearing `answer` tool — bound instantaneous abuse:
91
+ Full rate-limit configuration for a profile:
44
92
 
45
93
  ```yaml
46
- mcp:
47
- application:
48
- mountPath: /mcp
49
- rateLimit:
50
- perClientPerSecond: 0.5 # 30/minute sustained per client
51
- perClientBurst: 5
94
+ mcp.operations.rateLimit.perToolPerSecond: 10
95
+ mcp.operations.rateLimit.perToolBurst: 20
96
+ mcp.operations.rateLimit.sessionConcurrency: 25
97
+ mcp.operations.rateLimit.sessionPerSecond: 100
98
+ mcp.operations.rateLimit.perClientPerSecond: 5
99
+ mcp.operations.rateLimit.perClientBurst: 10
100
+ mcp.operations.rateLimit.initializePerSecond: 10
101
+ mcp.operations.rateLimit.initializeBurst: 50
102
+ mcp.operations.rateLimit.identityHeader: 'x-forwarded-for'
52
103
  ```
53
104
 
54
- Behind a proxy that manages `X-Forwarded-For` correctly:
105
+ Fractional per-client rate (6 calls per minute) with default burst:
55
106
 
56
107
  ```yaml
57
- mcp:
58
- application:
59
- rateLimit:
60
- identityHeader: x-forwarded-for
61
- perClientPerSecond: 0.5
108
+ mcp.application.rateLimit.perClientPerSecond: '0.1'
109
+ # perClientBurst defaults to 1 (floored from 0.1)
62
110
  ```
111
+
112
+ ## Notes
113
+
114
+ | Key | Type | Default (operations / application) |
115
+ | --------------------- | --------------- | ----------------------------------- |
116
+ | `perToolPerSecond` | number (min 0) | `10` / `25` |
117
+ | `perToolBurst` | number (min 0) | `20` / `50` |
118
+ | `sessionConcurrency` | integer (min 0) | `25` / `50` |
119
+ | `sessionPerSecond` | number (min 0) | `100` / `200` |
120
+ | `perClientPerSecond` | number (min 0) | `0` (disabled) |
121
+ | `perClientBurst` | number (min 0) | `perClientPerSecond` floored at `1` |
122
+ | `initializePerSecond` | number (min 0) | `10` |
123
+ | `initializeBurst` | number (min 1) | `50` |
124
+ | `identityHeader` | string | unset (socket IP) |
125
+
126
+ - 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"`.
127
+ - 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.
128
+ - The operations profile is served by the main thread only, so it admits exactly the configured figure.
129
+ - For quotas that survive restarts and are shared across workers, see [durable-quotas.md](durable-quotas.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@harperfast/template-vue-studio",
3
- "version": "1.13.6",
3
+ "version": "1.13.7",
4
4
  "type": "module",
5
5
  "repository": "github:HarperFast/create-harper",
6
6
  "scripts": {},
package/skills-lock.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "source": "harperfast/skills",
6
6
  "sourceType": "github",
7
7
  "skillPath": "harper-best-practices/SKILL.md",
8
- "computedHash": "c948588fe89c745233c8676f649ead8fae84012bff0a276a2f8fb98bcaa6dfdf"
8
+ "computedHash": "a03b4d9d7337d9e49bc0280b5c5bfc76d5330352af39ad5b50fd208659b04dd6"
9
9
  },
10
10
  "harper-local-dev": {
11
11
  "source": "harperfast/skills",
@@ -17,7 +17,7 @@
17
17
  "source": "harperfast/skills",
18
18
  "sourceType": "github",
19
19
  "skillPath": "harper-mcp/SKILL.md",
20
- "computedHash": "397b88d772506560acf6315408656d15eb20bcc540bdaa286574c00d7b3e8268"
20
+ "computedHash": "1c6cc3a54399f881f78d7c92884f2d192e2c6600cb2af10ae6a0196d0687e0c3"
21
21
  }
22
22
  }
23
23
  }