@cratis/pi 7.155.0 → 7.156.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.
@@ -79,6 +79,7 @@
79
79
  "cratis-arc-configuration",
80
80
  "cratis-arc-ef-core-migration",
81
81
  "cratis-arc-hosting",
82
+ "cratis-arc-mcp",
82
83
  "cratis-arc-neo4j",
83
84
  "cratis-arc-observable-query-http",
84
85
  "cratis-arc-query-paging",
@@ -0,0 +1,261 @@
1
+ ---
2
+ name: cratis-arc-mcp
3
+ description: Use when exposing Arc commands or queries to AI agents as MCP tools, naming, describing and scoping those tools, or connecting Claude, VS Code or MCP Inspector with a personal access token. Not for Chronicle's own MCP server or authoring the command itself (cratis-arc-command).
4
+ license: MIT
5
+ ---
6
+
7
+ <!-- Copyright (c) Cratis. All rights reserved. -->
8
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
9
+
10
+ # Expose Arc commands and queries over MCP
11
+
12
+ `Cratis.Arc.Mcp` serves an MCP endpoint from an Arc application. An agent calls
13
+ the commands and queries you declare, as the verified caller the capability gate
14
+ admitted. Nothing is exposed unless declared, and the tool set is frozen at
15
+ startup.
16
+
17
+ Requires: the `Cratis.Arc.Mcp` package, capability hosting, and a verified-caller
18
+ installation (`WithPersonalAccessTokens(...)` or `WithVerifiedCallers(...)`).
19
+
20
+ ## Decide what to expose
21
+
22
+ 1. Expose queries first. A query tool is annotated read-only and idempotent.
23
+ 2. Expose a command only when an agent acting for a user should be able to do
24
+ what the command does. The command's own authorization still applies, but
25
+ exposure is a product decision. Least privilege: the smallest set of tools,
26
+ each with the narrowest scopes.
27
+ 3. Never expose a command that needs approval (`[RequiresApproval]`, inherited).
28
+ Startup fails with `McpApprovalRequiredCommandExposed`.
29
+ 4. Streaming (observable) queries are not available as tools; a call returns
30
+ "The tool is not available on this host."
31
+ 5. Do not expose by default or by convention. A new operation stays unexposed
32
+ until someone adds the declaration.
33
+
34
+ ## Declare the tool
35
+
36
+ Default: the attribute, next to the code. It applies to a command class or a
37
+ read model query method, once, and is not inherited.
38
+
39
+ ```csharp
40
+ using System.ComponentModel;
41
+ using Cratis.Arc.Commands.ModelBound;
42
+ using Cratis.Arc.Mcp;
43
+ using Cratis.Arc.Queries.ModelBound;
44
+
45
+ [Command]
46
+ [ExposeOverMcp("add_note", Description = "Adds a note and returns its id.")]
47
+ public record AddNote([property: Description("The note text, plain text.")] string Text)
48
+ {
49
+ public Guid Handle() => Guid.NewGuid();
50
+ }
51
+
52
+ [ReadModel]
53
+ public record NoteReadModel(string Text)
54
+ {
55
+ [ExposeOverMcp("list_notes", Description = "Lists notes, newest first. Use page_size to limit the result.")]
56
+ public static IQueryable<NoteReadModel> All() => Enumerable.Empty<NoteReadModel>().AsQueryable();
57
+ }
58
+ ```
59
+
60
+ Use the builder only when the type cannot carry the attribute:
61
+ `mcp.Expose<AddNote>("add_note", "Adds a note.")` and
62
+ `mcp.ExposeQuery<NoteReadModel>(nameof(NoteReadModel.All), "list_notes", "Lists notes.")`.
63
+ The method name is checked at startup (`McpExposedOperationUnknown`); the string
64
+ overload `ExposeQuery("Ns.Type.Method", ...)` is obsolete, do not use it.
65
+
66
+ Only a command that has `[Command]` **and** a `Handle` method, and a read
67
+ model (`[ReadModel]`) query method, are discoverable. Without them the tool is
68
+ not found.
69
+
70
+ ## Name and describe
71
+
72
+ - Name matches `^[a-z][a-z0-9_]{0,63}$` and is unique (`McpToolNameInvalid`,
73
+ `McpToolNameDuplicated`). Names are explicit and never derived from the CLR
74
+ name. Treat them as public API: clients and prompts store them. Renaming a
75
+ class does not rename the tool; renaming the tool breaks clients.
76
+ - The tool description is required (`McpToolDescriptionMissing`). It is the only
77
+ guidance the agent gets: one sentence on the effect, the inputs that must be
78
+ right, what comes back. No secrets, internal names or instructions about
79
+ other tools.
80
+ - Put `[Description("...")]` (`System.ComponentModel`) on every command
81
+ property (`[property: Description]` on a record parameter) and every query
82
+ method parameter. It becomes the argument's `description` in the input
83
+ schema. Arc does not infer it from names or XML comments.
84
+ - Query tools take the query parameters as arguments; paging applies only to
85
+ queries returning `IQueryable<T>`; those tools accept `page_size` (optional
86
+ `page`). An `IEnumerable<T>` query has no paging arguments and supplying them
87
+ is an invalid-arguments error. Argument values are scalars, or arrays
88
+ for collection parameters.
89
+
90
+ ## Scopes
91
+
92
+ | Tool | Always requires |
93
+ |---|---|
94
+ | Query | `ReadScope` |
95
+ | Command | `WriteScope` |
96
+
97
+ Defaults are `<ApplicationName>:read` and `<ApplicationName>:write`. With no
98
+ application name and no explicit scope, startup fails with `McpToolHasNoScope`.
99
+
100
+ - Add requirements with `[RequiresScope("notes:restricted-read")]`
101
+ (`Cratis.Arc.Authorization`); repeatable, the caller must hold all of them.
102
+ The attribute targets classes and methods only: put it on the command type or
103
+ its handler method, and on the read model type, the performer type or the
104
+ query method. It cannot go on a parameter.
105
+ - `WriteScopes` lists additional write scopes; `WriteScope` is always one. An
106
+ entry must not be blank, repeated or equal to `ReadScope`
107
+ (`McpOptionsInvalid`).
108
+ - `IMcpToolAuthorizer` (`AddToolAuthorizer<T>()`) handles rules a scope cannot
109
+ express. It only narrows: it runs after scopes pass, filters `tools/list`
110
+ and refuses calls (HTTP 403 `forbidden`). It cannot grant.
111
+ - Every scope a tool requires, including `[RequiresScope]` extras, must be in
112
+ `PatOptions.AllowedScopes`, or no PAT can call the tool. The list is empty by
113
+ default, case-sensitive, with no wildcards. A scope with an `admin` or
114
+ `approve` segment (split on `:`, `.`, `/`, `-`) is never allowed on a PAT,
115
+ so a tool that requires one cannot be called with a PAT at all. Use a name
116
+ such as `notes:restricted-read`, not `notes:admin-read`.
117
+ - Startup logs warning event 5103 (`MCP requires scope '<scope>', which
118
+ PatOptions.AllowedScopes does not allow. PATs cannot satisfy this tool
119
+ scope.`) once per missing scope, only for a tool that no scope set in
120
+ `AllowedScopes` satisfies (required scopes and every alternative set are
121
+ checked). Startup still succeeds and no PAT can call that tool. Fix: add the
122
+ scope to `AllowedScopes`, or change the tool's scopes. Without a PAT
123
+ installation the check does not run.
124
+
125
+ ## Host setup (summary)
126
+
127
+ Choose the verified-caller installation first:
128
+
129
+ - **PAT-only** (default for MCP): `WithPersonalAccessTokens(options, callers => callers.ForResource(...).UsePersonDirectory<T>())`.
130
+ No forwarding configuration and no `AllowPersonalAccessTokenCallers()`;
131
+ adding forwarding here throws `InvalidVerifiedCallerInstallation`.
132
+ - **PAT plus signed browser issuance**: add `UseSignedForwardedIdentityV2(...)`
133
+ **and** `AllowPersonalAccessTokenCallers()`. The opt-in without forwarding
134
+ configuration throws `InvalidVerifiedCallerInstallation`. Use this only when
135
+ the same host issues PATs to signed browser sessions; see the reference.
136
+
137
+ PAT-only installation:
138
+
139
+ ```csharp
140
+ builder.AddCratisArc(
141
+ options => options.EndpointGroups.Assign("capabilities", capabilityPort),
142
+ configureBuilder: arc => arc
143
+ .WithCapabilities()
144
+ .WithPersonalAccessTokens(
145
+ new PatOptions("stage-notes") { AllowedScopes = ["notes:read", "notes:write"] },
146
+ callers => callers
147
+ .ForResource("https://notes.example.test", "notes", "production")
148
+ .UsePersonDirectory<PersonDirectory>())
149
+ .WithMcp(mcp => mcp.Configure(o =>
150
+ {
151
+ o.ApplicationName = "notes";
152
+ o.PublicOrigin = "https://notes.example.test";
153
+ })));
154
+
155
+ var app = builder.Build();
156
+ app.UseCratisArc();
157
+ app.MapArcMcp();
158
+ ```
159
+
160
+ Read [references/setup-and-profiles.md](references/setup-and-profiles.md) for
161
+ the full prerequisites (ports and listeners, gating, verified
162
+ callers), the credential profiles, `Origin` and `AllowedOrigins`, and the
163
+ development PAT adapters.
164
+
165
+ Rules to keep in mind:
166
+
167
+ - The `PatOptions` resource key must be `direct`, `studio` or `stage-<app>`
168
+ (`<app>`: lowercase letters, digits and hyphens, 1 to 48 characters, starting
169
+ and ending with a letter or digit). Any other key, such as `local` or
170
+ `notes`, throws `ArgumentException`.
171
+ - Use `WithCapabilities()` without a `GatedEndpoints` selector: the whole
172
+ capabilities port is then gated after routing, including health and readiness
173
+ probes (only OAuth resource metadata stays anonymous). Selective gating is an
174
+ explicit opt-out: set `CapabilitiesOptions.GatedEndpoints` to a selector
175
+ (`WithMcp` adds MCP to it) and keep other routes you need outside the gate.
176
+ - The endpoint is served only on the capabilities port. Bind a listener on it
177
+ as well as the default listener.
178
+ - Default profile `PatOnly` suits CLI and IDE clients. Hosted connectors cannot
179
+ be handed a PAT; they need `OAuthOnly` or `Combined` plus your own OAuth
180
+ authorization server.
181
+ - `UseDevelopmentPersonalAccessTokenAdapters()` is Development-only: in-memory,
182
+ lost on restart, host startup throws elsewhere. Never combine with
183
+ production adapters. It is the only public development PAT type; the adapter
184
+ classes behind it are internal, so never reference them. A production host
185
+ implements the public `IPatAuthority`, `IPatPolicy` and `IPatRecoveryEpoch`.
186
+ - Keep `ExclusiveTools = true` (default). Turning it off serves tools outside
187
+ the ceiling with no scope checks.
188
+ - Keep `AllowedOrigins` empty unless a browser client needs it.
189
+
190
+ ## What the agent sees
191
+
192
+ - A request with no accepted caller, or a credential kind the profile refuses,
193
+ gets HTTP 401 `unauthorized` before any tool list. Its `WWW-Authenticate`
194
+ carries the realm (`PatOnly`) or the resource metadata URL, not scopes.
195
+ - `tools/list` shows only tools whose scopes the caller holds and every
196
+ authorizer allows. A token with only the read scope never sees a command
197
+ tool; a token with no MCP scopes gets an empty list.
198
+ - `inputSchema` is generated from the command properties or query parameters
199
+ and rejects undeclared arguments. Query tools are annotated read-only and
200
+ idempotent; command tools destructive and not idempotent.
201
+ - A result carries the same JSON as text and as `structuredContent` matching
202
+ `outputSchema`: `outcome` (`isSuccess`, `isAuthorized`, `isValid`,
203
+ `validationResults`) plus `response` (commands) or `data` and `paging`
204
+ (queries). Validation failures and refusals are tool errors, not HTTP errors.
205
+ - A call outside the caller's scopes is HTTP 403 `insufficient_scope`; the
206
+ `WWW-Authenticate` `scope` value lists all scopes the tool requires, not only
207
+ the missing ones.
208
+ - Exceptions come back as the generic "The tool failed."; no message leaks.
209
+
210
+ ## Audit log
211
+
212
+ Every `tools/call` writes one Information entry in the
213
+ `Cratis.Arc.Mcp.McpCallAudit` category (event 5102): tool, kind, person,
214
+ tenant, credential id and kind, outcome, correlation id. Never the token,
215
+ arguments or results. Outcomes: `succeeded`, `failed`, `insufficient_scope`,
216
+ `not_allowed`, `invalid_arguments`, `malformed`, `error`. Person and tenant are
217
+ personal data; set log retention accordingly. A request with no accepted
218
+ caller is not audited.
219
+
220
+ ## Verify
221
+
222
+ 1. Run the host. Startup validates every tool and throws an
223
+ `InvalidMcpConfiguration` subclass for the first problem. A pass is a host
224
+ that starts. Authorization declarations are validated for every command and
225
+ query, not just exposed ones.
226
+ 2. List tools: `curl -s <url> -H "Authorization: Bearer $PAT" -H "Content-Type: application/json" -H "Accept: application/json, text/event-stream" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`.
227
+ Pass: your tool names appear; a read-only token omits command tools.
228
+ 3. Interactive check: `npx @modelcontextprotocol/inspector`, transport
229
+ Streamable HTTP, URL `https://<host>:<capabilityPort>/mcp`, header
230
+ `Authorization: Bearer <token>`. A browser Inspector sends an `Origin`; see
231
+ the reference for `AllowedOrigins`. Remove the entry afterwards.
232
+ 4. Specs: follow the host pattern in `Source/DotNET/Arc.Mcp.Specs` of the Arc
233
+ repository (real host on the capabilities port, a substituted
234
+ `IVerifiedCallerAccessor`). Cover a read-only caller, a caller missing a
235
+ `[RequiresScope]`, and a denying `IMcpToolAuthorizer`.
236
+
237
+ ## Common mistakes
238
+
239
+ | Mistake | Symptom |
240
+ |---|---|
241
+ | No `[Command]` or no `Handle` | `McpExposedOperationUnknown` |
242
+ | `ExposeQuery<T>` method name that does not exist | `McpExposedOperationUnknown` at startup |
243
+ | No description | `McpToolDescriptionMissing` |
244
+ | No `ApplicationName`, `ReadScope` or `WriteScope` | `McpToolHasNoScope` |
245
+ | MCP scopes missing from `PatOnly` `AllowedScopes` | 401 for a PAT that looks right; warning event 5103 at startup when no PAT can satisfy a tool |
246
+ | Probes left on the capabilities port with `GatedEndpoints` unset | Probes require a verified caller; move them or set an explicit selector |
247
+ | Listener not bound on the capabilities port | Not found on the default port, or no connection |
248
+ | Exposing a `[RequiresApproval]` command | `McpApprovalRequiredCommandExposed` |
249
+ | Browser client without `AllowedOrigins` | 403 `origin_not_allowed` |
250
+ | Hosted connector on `PatOnly` | 401, no metadata (404 on the well-known URL) |
251
+ | Development adapters in a non-Development host | Startup `InvalidOperationException` |
252
+ | Argument description missing | Agent guesses the argument |
253
+
254
+ Read [references/troubleshooting.md](references/troubleshooting.md) for the
255
+ complete error, HTTP status and tool error tables.
256
+
257
+ ## Related skills
258
+
259
+ - `cratis-arc-command` for the command and its handler.
260
+ - `cratis-arc-query-paging` for query paging that `page` and `page_size` map to.
261
+ - `cratis-arc-hosting` for application hosting and `cratis-arc-authentication-authorization-and-identity` for authorization policies.
@@ -0,0 +1,191 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # MCP host setup, credential profiles and origins
5
+
6
+ ## Contents
7
+
8
+ - Prerequisites
9
+ - Issuing a token
10
+ - Listeners and the capabilities port
11
+ - Credential profiles
12
+ - OAuth and Combined options
13
+ - Origin check and AllowedOrigins
14
+ - Development PAT adapters
15
+ - Curated tool sources
16
+
17
+ ## Prerequisites
18
+
19
+ MCP serving needs all of these. Registration order does not matter; the check
20
+ runs when the host starts.
21
+
22
+ - Capability hosting: `WithCapabilities(...)`.
23
+ - A port for the capabilities endpoint group:
24
+ `options.EndpointGroups.Assign("capabilities", port)`.
25
+ - `GatedEndpoints` is optional. Unset (the default), every endpoint on the
26
+ capabilities port is gated after routing, including health and readiness
27
+ probes; only the OAuth protected resource metadata route stays anonymous.
28
+ Selective gating is an explicit opt-out: set
29
+ `CapabilitiesOptions.GatedEndpoints` to a `CapabilityEndpointSelector` and
30
+ `WithMcp` adds MCP to that selection, leaving other routes outside the gate.
31
+ Missing capability hosting throws `McpRequiresCapabilities`.
32
+ - A verified-caller installation: `WithPersonalAccessTokens(PatOptions, callers => ...)`
33
+ or `WithVerifiedCallers(...)`. Startup does not check that one is present;
34
+ without it no caller is admitted.
35
+ - For PATs: `IPatAuthority`, `IPatRecoveryEpoch` and `IPatPolicy` must be
36
+ registered, or issuance and verification are refused. Use
37
+ `UseDevelopmentPersonalAccessTokenAdapters()` locally; production needs durable
38
+ storage, product policy and recovery evidence.
39
+ - Arc has no issuance endpoint. Your endpoint calls
40
+ `IPersonalAccessTokens.Issue(lifetime, scopes, cancellationToken)`. Maximum
41
+ lifetime is 90 days; `Token.Reveal()` returns the token once. See
42
+ "Issuing a token" below for what the call requires.
43
+ - Two installations exist (`VerifiedCallersBuilder`): PAT-only (person
44
+ directory, no forwarding, no opt-in) and PAT plus signed browser issuance
45
+ (`UseSignedForwardedIdentityV2(v2 => v2.WithRealmIssuer(...)
46
+ .WithTenantHeader(...).AddPublicKey(keyId, publicKeyPem)
47
+ .UseProcessLocalNonceStore())` together with
48
+ `AllowPersonalAccessTokenCallers()`, plus the forwarding-hop client
49
+ certificate configuration). Mixing them throws
50
+ `InvalidVerifiedCallerInstallation`. Do not also call `WithVerifiedCallers`;
51
+ a second installation is rejected. Process-local nonce storage is a
52
+ single-process development choice. Full example: the PAT adapter guide,
53
+ section "Compose browser issuance and PAT callers".
54
+ - `PatOptions.AllowedScopes` must list every scope an MCP tool requires. The
55
+ `PatOptions` resource key must be `direct`, `studio` or `stage-<app>`
56
+ (`<app>`: lowercase letters, digits, hyphens, 1 to 48 characters, starting
57
+ and ending with a letter or digit); `local` is invalid and throws
58
+ `ArgumentException`. Startup logs warning event 5103 for a tool no PAT can
59
+ satisfy; see the troubleshooting reference.
60
+
61
+ ## Issuing a token
62
+
63
+ `Issue` succeeds only when all of these hold:
64
+
65
+ - The current caller is a verified `BrowserSession` or `OAuthGrant` caller
66
+ with an owner (person, account key, tenant) for this resource. A PAT cannot
67
+ issue another PAT.
68
+ - The caller carries valid assurance facts (the PAT module checks them).
69
+ - The lifetime is positive and within `PatOptions.MaximumLifetime` and 90 days.
70
+ - Every requested scope is in `PatOptions.AllowedScopes` **and** held by the
71
+ issuing caller (a caller cannot mint a scope it does not hold).
72
+ - The three adapters are registered and the policy permits the record.
73
+
74
+ Otherwise the result is a refusal code such as `pat_issuance_refused`,
75
+ `pat_policy_refused`, `pat_commit_refused` or `pat_authority_unavailable`.
76
+
77
+ Limits to state to the user, not to work around:
78
+
79
+ - AuthProxy does not sign v2 forwarded identity yet; the v2 contract is a
80
+ specification and the producer is not implemented. A real signed browser
81
+ caller for issuance therefore has no released producer.
82
+ - The development adapters replace the three PAT ports only. They do not
83
+ bootstrap issuance: you still need a verified browser or OAuth caller.
84
+ - Synthetic signing (`TestSigner` in `Samples/VerifiedCallerAcceptance.Specs`)
85
+ is a spec-only test pattern. Never add a development signer, a debug
86
+ endpoint or any issuance bypass to an application, and never ship signing
87
+ keys that let a client mint callers.
88
+ - Without an issuance path, say so and stop; do not fabricate a token.
89
+
90
+ ## Listeners and the capabilities port
91
+
92
+ Assigning the port does not bind it. Bind both the default public listener and a
93
+ listener on the capabilities port (Kestrel or `UseUrls`), even when the host
94
+ serves only `/mcp`. A request on the default port is not served. Map the
95
+ endpoint with `app.MapArcMcp()` after `app.UseCratisArc()`.
96
+
97
+ ## Credential profiles
98
+
99
+ `McpOptions.Profile` selects the accepted credential kind.
100
+
101
+ | Profile | Accepts | Use for |
102
+ |---|---|---|
103
+ | `PatOnly` (default) | Personal access tokens | Command-line and IDE clients (Claude Code, Claude Desktop through `mcp-remote`, VS Code) |
104
+ | `OAuthOnly` | OAuth access tokens | Hosted connectors |
105
+ | `Combined` | Both, each by its own verifier | Hosted connectors while PATs keep working |
106
+
107
+ A caller verified with another credential kind (a browser session) is refused
108
+ with the same 401 as an unauthenticated request. Arc does not provide an OAuth
109
+ authorization server: it verifies grants through your installation and
110
+ publishes protected resource metadata; your own server issues tokens. Whether a
111
+ given connector can register with that server is outside Arc.
112
+
113
+ Client configuration for PAT clients: send `Authorization: Bearer <token>`.
114
+ Claude Code: `claude mcp add --transport http notes <url> --header "Authorization: Bearer $PAT"`.
115
+ VS Code: `.vscode/mcp.json` with `"type": "http"`, `url` and a `headers` entry
116
+ fed from a `promptString` input with `"password": true`. Never commit a token.
117
+
118
+ ## OAuth and Combined options
119
+
120
+ ```csharp
121
+ mcp.Configure(o =>
122
+ {
123
+ o.ApplicationName = "notes";
124
+ o.Profile = McpProfile.Combined;
125
+ o.PublicOrigin = "https://notes.example.test";
126
+ o.Resource = "https://notes.example.test/mcp";
127
+ o.AuthorizationServers.Add("https://login.example.test");
128
+ });
129
+ ```
130
+
131
+ - `PublicOrigin` is required: an origin (no path, query, fragment), `https`
132
+ (`http` only for loopback).
133
+ - `Resource` must equal `PublicOrigin` plus `Path` (default `/mcp`).
134
+ - `AuthorizationServers` needs at least one absolute `https` URL (loopback may
135
+ be `http`), no query, fragment or user info.
136
+ - Metadata is served at `/.well-known/oauth-protected-resource/mcp` and lists
137
+ `resource`, `authorization_servers` and `scopes_supported` (the read scope and
138
+ write scopes unless `ScopesSupported` is set).
139
+ - An unauthenticated request gets `WWW-Authenticate: Bearer resource_metadata="..."`.
140
+ Under `PatOnly` the metadata URL answers 404 `not_found`.
141
+ - These values are never derived from the request host.
142
+
143
+ Invalid options throw `McpOptionsInvalid` naming the option and profile.
144
+
145
+ ## Origin check and AllowedOrigins
146
+
147
+ Every request's `Origin` header is checked. No `Origin` (command-line and
148
+ desktop clients) is allowed. Allowed set: `PublicOrigin` plus `AllowedOrigins`.
149
+ Anything else is 403 `origin_not_allowed`, under every profile.
150
+
151
+ ```csharp
152
+ mcp.Configure(o => o.AllowedOrigins.Add("http://localhost:6274")); // Inspector, test runs only
153
+ ```
154
+
155
+ - Entries are bare origins: scheme, host, optional port; `https`, or `http` for
156
+ loopback.
157
+ - Comparison ignores case. Several `Origin` values, or `null`, are always
158
+ refused.
159
+ - Set the `Cratis.Arc.Mcp` log category to Debug: `McpAdmission` (event 5101)
160
+ logs the refused origin and the reason, so copy the exact origin from there.
161
+ - The Inspector may connect through its own proxy process, which sends no
162
+ `Origin`; then no entry is needed.
163
+ - Keep production `AllowedOrigins` empty unless a real browser client needs it.
164
+
165
+ ## Development PAT adapters
166
+
167
+ `UseDevelopmentPersonalAccessTokenAdapters()`
168
+ (`Cratis.Arc.PersonalAccessTokens.Development`) registers process-local
169
+ `IPatAuthority`, `IPatPolicy` and `IPatRecoveryEpoch`. It follows
170
+ `WithPersonalAccessTokens` in any order and uses its limits.
171
+
172
+ - This extension method is the only public development PAT type. The
173
+ authority, policy and recovery-epoch classes it registers are internal: do
174
+ not reference or construct them.
175
+ - Credentials live in memory and disappear on restart.
176
+ - Host startup throws `InvalidOperationException` outside the Development
177
+ environment, and each adapter also fails closed there.
178
+ - Never combine them with production adapters.
179
+ - They replace the adapters only; they do not bootstrap issuance. Issuing a
180
+ token still needs a verified browser or OAuth caller (see "Issuing a
181
+ token").
182
+
183
+ ## Curated tool sources
184
+
185
+ For a tool that is not a plain command or query, implement `IMcpToolSource`
186
+ (`AddToolSource<T>()`), build descriptors with
187
+ `McpToolDescriptor.Custom(name, description, scopes, McpToolAccess.Read|Write)`.
188
+ A tool that writes must require `WriteScope` or one of `WriteScopes` in every
189
+ scope set it declares (`McpWriteToolLacksWriteScope`). `AlternativeScopes`
190
+ adds alternative scope sets. Read caller, tenant and scopes only from
191
+ `invocation.Caller`, never from the request.
@@ -0,0 +1,86 @@
1
+ <!-- Copyright (c) Cratis. All rights reserved. -->
2
+ <!-- Licensed under the MIT license. See LICENSE file in the project root for full license information. -->
3
+
4
+ # MCP troubleshooting tables
5
+
6
+ ## Contents
7
+
8
+ - Startup errors
9
+ - HTTP errors
10
+ - Tool errors
11
+ - Empty or incomplete tool list
12
+
13
+ ## Startup errors
14
+
15
+ Validation runs in order; fix the first error.
16
+
17
+ | Exception or message | Cause | Fix |
18
+ |---|---|---|
19
+ | `McpRequiresCapabilities` | `WithMcp` without capability hosting | Add `WithCapabilities(...)` |
20
+ | `Capability endpoint group '<group>' has no port` | No port for the capabilities group | `EndpointGroups.Assign("capabilities", port)` |
21
+ | Health or readiness probe on the capabilities port is rejected | `GatedEndpoints` unset gates the whole port | Move probes off the capabilities port, or set an explicit `GatedEndpoints` selector (`WithMcp` adds `/mcp`) |
22
+ | `McpOptionsInvalid` | An option is invalid for the profile | OAuth profiles: `PublicOrigin`, `Resource` = `PublicOrigin` + `Path`, `AuthorizationServers`. Also bad `WriteScopes` |
23
+ | `McpToolNameInvalid` | Name outside `^[a-z][a-z0-9_]{0,63}$` | Lowercase letters, digits, underscores, start with a letter |
24
+ | `McpToolNameDuplicated` | Duplicate name | Rename one |
25
+ | `McpToolDescriptionMissing` | No description | Add `Description` or the builder argument |
26
+ | `McpExposedOperationUnknown` | Wrong `ExposeQuery<T>` method name, or the command has no handler | `nameof(ReadModel.Method)`; add `[Command]` and `Handle` |
27
+ | `McpApprovalRequiredCommandExposed` | Command has `[RequiresApproval]` | Do not expose it |
28
+ | `McpToolHasNoScope`, `McpToolScopeBlank` | No application name or explicit scope; blank scope | Set `ApplicationName`, or `ReadScope` and `WriteScope` |
29
+ | `McpWriteToolLacksWriteScope` | A write tool (usually curated) needs only read scopes | Require `WriteScope` or a `WriteScopes` entry |
30
+ | `McpToolNameTakenByServerTool` | Name clash with a tool registered on the MCP server | Rename one |
31
+ | `McpToolOutputSchemaInvalid` | Curated `OutputSchema` is not a JSON object schema | Fix the schema |
32
+ | Startup fails for a command you did not expose | Authorization is validated for every discovered command and query | Fix the missing or invalid policy it names |
33
+
34
+ Warning event 5103 at startup: `MCP requires scope '<scope>', which
35
+ PatOptions.AllowedScopes does not allow. PATs cannot satisfy this tool scope.`
36
+ It is logged once per missing scope, and only for a tool that no scope set in
37
+ `AllowedScopes` satisfies (required scopes and every alternative set are
38
+ checked). A tool a PAT can already satisfy raises no warning. Startup still
39
+ succeeds; no PAT can call that tool. Fix: add the scope to
40
+ `PatOptions.AllowedScopes`, or adjust `ReadScope`/`WriteScope` and the tool's
41
+ scope declarations. A scope with an `admin` or `approve` segment can never be
42
+ allowed on a PAT. Without a PAT installation the check does not run.
43
+
44
+ `PatOptions` with a resource key other than `direct`, `studio` or `stage-<app>`
45
+ (for example `local`) throws `ArgumentException` ("Invalid PAT resource key.").
46
+
47
+ ## HTTP errors
48
+
49
+ | Status and body | Cause | Fix |
50
+ |---|---|---|
51
+ | 403 `origin_not_allowed` | `Origin` not `PublicOrigin` or in `AllowedOrigins` | Add the exact origin; Debug log of `McpAdmission` shows it |
52
+ | 401 `unauthorized` | No caller, or a credential kind the profile refuses. `WWW-Authenticate` has the realm (`PatOnly`) or the metadata URL, no scopes | Send `Authorization: Bearer <PAT>`; check expiry and revocation |
53
+ | 401 for a PAT that looks right | Token holds a scope not in `AllowedScopes` | Add every MCP scope, issue a new token |
54
+ | 403 `insufficient_scope` | Tool needs a scope the caller lacks | Issue a token with the scopes in `WWW-Authenticate` (it lists all scopes the tool requires, not only the missing ones) |
55
+ | 403 `forbidden` | An `IMcpToolAuthorizer` denied the call | Check the authorizer rule |
56
+ | 404 `not_found` on the well-known URL | Profile is `PatOnly` | Use `OAuthOnly` or `Combined` |
57
+ | 405 `method_not_allowed` | GET or DELETE on the path | POST only |
58
+ | 413 `request_too_large` | Body over `MaxRequestBodySize` (1 MiB) | Send less, or raise the option |
59
+ | 400 `invalid_request` | Invalid JSON, duplicate members, JSON-RPC batch | One message per request |
60
+ | Refused on the default port | MCP is served only on the capabilities port | Use that port and bind a listener on it |
61
+
62
+ ## Tool errors
63
+
64
+ A tool failure is a result with `isError`, not an HTTP error.
65
+
66
+ | Text | Cause | Fix |
67
+ |---|---|---|
68
+ | `The arguments are not valid for this tool.` | Missing, mistyped or undeclared argument | Match `inputSchema` |
69
+ | `The caller lacks a scope this tool requires.` | Scope check failed at the tool | Issue a token with the scopes |
70
+ | `The caller is not allowed to call this tool.` | Authorizer or operation authorization refused | Check authorization |
71
+ | `The tool failed.` | The operation threw | Read the server log |
72
+ | `The tool is not available on this host.` | Streaming query, or a replaced command or query pipeline | Expose a non-streaming query; use Arc's pipelines |
73
+ | Result with `isValid: false` | Command validation failed | Read `validationResults` |
74
+
75
+ ## Empty or incomplete tool list
76
+
77
+ A request with no accepted caller is refused with 401 before any list. For an
78
+ admitted caller, `tools/list` shows only tools its scopes and authorizers
79
+ allow. An empty list has three possible causes:
80
+
81
+ 1. The token holds none of the exposed tools' scopes.
82
+ 2. Authorizers hide every tool.
83
+ 3. No tools are exposed.
84
+
85
+ A missing command tool means the token lacks the write scope or an
86
+ `IMcpToolAuthorizer` denies it.
@@ -279,6 +279,7 @@
279
279
  "cratis-arc-command-validation",
280
280
  "cratis-arc-configuration",
281
281
  "cratis-arc-hosting",
282
+ "cratis-arc-mcp",
282
283
  "cratis-arc-neo4j",
283
284
  "cratis-arc-observable-query-http",
284
285
  "cratis-arc-query-paging"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cratis/pi",
3
- "version": "7.155.0",
3
+ "version": "7.156.0",
4
4
  "description": "Configuration-aware Cratis AI integration for Pi",
5
5
  "type": "module",
6
6
  "files": [