@gjermundgaraba/effect-actions 0.5.0 → 0.7.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.
Files changed (43) hide show
  1. package/README.md +7 -6
  2. package/dist/Action.d.mts +16 -8
  3. package/dist/Action.mjs +0 -1
  4. package/dist/ActionCatalog.d.mts +2 -3
  5. package/dist/ActionCatalog.mjs +4 -5
  6. package/dist/ActionCli.mjs +5 -1
  7. package/dist/ActionCliClient.d.mts +8 -9
  8. package/dist/ActionCliClient.mjs +4 -11
  9. package/dist/ActionGroup.d.mts +15 -11
  10. package/dist/ActionGroup.mjs +8 -2
  11. package/dist/ActionHttp.d.mts +9 -5
  12. package/dist/ActionHttp.mjs +14 -9
  13. package/dist/ActionHttpClient.d.mts +33 -0
  14. package/dist/ActionHttpClient.mjs +16 -0
  15. package/dist/ActionMcp.d.mts +16 -26
  16. package/dist/ActionMcp.mjs +12 -8
  17. package/dist/ActionToolkit.d.mts +10 -11
  18. package/dist/Testing.d.mts +35 -4
  19. package/dist/Testing.mjs +53 -6
  20. package/dist/TestingClient.d.mts +6 -5
  21. package/dist/TestingClient.mjs +6 -3
  22. package/dist/internal/actions.d.mts +18 -7
  23. package/dist/internal/actions.mjs +11 -1
  24. package/dist/internal/fetchClient.d.mts +6 -0
  25. package/dist/internal/fetchClient.mjs +8 -0
  26. package/dist/internal/implementation.d.mts +14 -15
  27. package/dist/internal/implementation.mjs +6 -5
  28. package/dist/internal/tools.mjs +1 -1
  29. package/docs/Action.md +11 -10
  30. package/docs/ActionCatalog.md +9 -9
  31. package/docs/ActionCli.md +7 -7
  32. package/docs/ActionCliClient.md +4 -4
  33. package/docs/ActionGroup.md +24 -16
  34. package/docs/ActionHttp.md +14 -12
  35. package/docs/ActionHttpClient.md +80 -0
  36. package/docs/ActionMcp.md +19 -22
  37. package/docs/ActionToolkit.md +1 -1
  38. package/docs/CONTEXT.md +4 -4
  39. package/docs/README.md +18 -18
  40. package/docs/Testing.md +27 -16
  41. package/docs/guarantees.md +5 -5
  42. package/docs/setup.md +7 -6
  43. package/package.json +5 -4
@@ -15,18 +15,20 @@ Import `@gjermundgaraba/effect-actions/ActionGroup`.
15
15
  | `app.group`, `app.build` | Bound contract and scoped handler acquisition. |
16
16
  | `contracts(...groups)` | Exact action types keyed by `<group>.<action>`. |
17
17
 
18
- Exported types: `Group`, `Any`, `Options`, `Implementation`, `Contracts`, `SchemaErrorPolicy`.
18
+ Exported types: `Group`, `Any`, `Options`, `Implementation`, `Contracts`, `SchemaErrorPolicy`,
19
+ `SchemaErrorAnswer`.
19
20
 
20
- The optional `schemaError` group option contains `errors` (policy error codecs) and
21
- `map(failure)` (a native `HttpApiSchemaError` to one of their decoded values). It affects HTTP only.
22
- Handler records require every action key. Each handler's input, success and declared errors
23
- come from its action; request requirements stay distinct from the builder's requirements.
21
+ The optional `schemaError` group option is a `SchemaErrorPolicy`: two answers, `invalid` and
22
+ `internal`, each a `schema` (a declared error codec) and `make(failure)` (the native
23
+ `HttpApiSchemaError` to that error's decoded value). The library decides which answer applies.
24
+ It affects HTTP only. Handler records require every action key. Each handler's input, success
25
+ and declared errors come from its action; request requirements stay distinct from the
26
+ builder's requirements.
24
27
 
25
28
  ## Canonical
26
29
 
27
30
  ```ts
28
31
  import { Effect, Schema } from "effect";
29
- import type { HttpApiError } from "effect/unstable/httpapi";
30
32
  import * as ActionGroup from "@gjermundgaraba/effect-actions/ActionGroup";
31
33
  import { CurrentActor } from "./auth.js";
32
34
  import { GetUser, RenameUser, WhoAmI } from "./contracts.js";
@@ -43,13 +45,17 @@ class InternalError extends Schema.TaggedError<InternalError>()(
43
45
  { httpApiStatus: 500 },
44
46
  ) {}
45
47
 
46
- // Shared across groups: annotate the parameter. Inline, `map` is inferred from `errors`.
48
+ // A request that does not decode is the caller's fault; a result that does not
49
+ // encode is the server's. Shared across groups as a constant.
47
50
  const schemaError = {
48
- errors: [InvalidRequest, InternalError],
49
- map: ({ kind }: HttpApiError.HttpApiSchemaError) =>
50
- kind === "Body" || kind === "ResponseHeaders"
51
- ? new InternalError({ message: "The request could not be completed." })
52
- : new InvalidRequest({ message: "The request does not match the action's input." }),
51
+ invalid: {
52
+ schema: InvalidRequest,
53
+ make: () => new InvalidRequest({ message: "The request does not match the action's input." }),
54
+ },
55
+ internal: {
56
+ schema: InternalError,
57
+ make: () => new InternalError({ message: "The request could not be completed." }),
58
+ },
53
59
  };
54
60
 
55
61
  export const UserActions = ActionGroup.make(
@@ -87,7 +93,7 @@ const renames: "renameUser" = contracts["users.renameUser"].name;
87
93
 
88
94
  - `name` matches `[A-Za-z0-9_-]+`, cannot be `then`, and must be unique within one `ActionHttp.make`. Action names must be unique within the group. MCP tool names must be unique within the group and within each Toolkit or MCP projection that serves it. Duplicates fail at `make`.
89
95
  - Group `errors` are appended to each action's own `errors`, so every handler of the group may fail with them. A failure that only the surface produces belongs on the adapter instead (`ActionHttp.make`'s `errors`, `ActionMcp`'s and `ActionToolkit`'s `errors`), not here.
90
- - `implement` takes a complete record or an Effect producing one. Every action must have a handler; missing keys are compile errors. Additional keys are not dispatched. It takes nothing else.
96
+ - `implement` takes a complete plain record or an Effect producing one. Every action must have a handler; missing keys are compile errors. A handler is an own-property function of the record: an inherited one, such as a class instance's method, does not count. A record that still lacks one at runtime (plain JavaScript, a cast: a missing key, `undefined`, any other non-function, an inherited method) throws at `implement`; a builder's record fails the adapter layer's build. Nothing is served with a handler missing. Handlers are called without a receiver. Additional keys are not dispatched. It takes nothing else.
91
97
  - The builder Effect runs once per adapter layer that serves the implementation, in that layer's scope. An implementation served by HTTP and MCP is built twice. Acquire shared state in a Layer you provide to the adapters, not in the builder.
92
98
  - Services yielded in the builder are build-time requirements (`RX`). Services yielded in a handler are request-time requirements (`R` of the handler). Adapters keep these separate in their types. Use distinct tags for each kind; never provide a request-identity tag at startup (see [guarantees.md](guarantees.md)).
93
99
  - `Implementation` is nominal. Spreading its properties does not produce an implementation. Each `implement` call is a separate binding.
@@ -97,8 +103,9 @@ const renames: "renameUser" = contracts["users.renameUser"].name;
97
103
  ### Schema-error policy
98
104
 
99
105
  - Without a policy, HTTP answers decoding and encoding failures with Effect's native empty 400.
100
- - With a policy, `map` receives the native `HttpApiSchemaError` (`kind`, `cause`) and returns one of `errors`. HTTP uses that error's `httpApiStatus`, and the error appears in `Http.api`, in clients, and in OpenAPI.
101
- - `kind` values: `Payload` (input decoding) and `Body` (success encoding). Actions declare no parameters, query, or headers, so no other kind occurs.
106
+ - With a policy, the library picks the answer from the native `HttpApiSchemaError`'s `kind`. Request-side kinds (`Payload`, `Params`, `Headers`, `Query`: the request did not decode) get `invalid`; response-side kinds (`Body`, `ResponseHeaders`: the handler's result did not encode) get `internal`. `make` receives the failure (`kind`, `cause`) and returns its schema's value. HTTP uses that error's `httpApiStatus`, and both errors appear in `Http.api`, in clients, and in OpenAPI.
107
+ - In practice only `Payload` and `Body` occur: actions declare no parameters, query, or headers, and no response headers.
108
+ - `invalid` and `internal` may share one schema; it is declared once.
102
109
  - MCP is unaffected. The native `McpServer` answers invalid arguments and unencodable results itself.
103
110
  - Policy errors extend the transport contract, not the handler contract. A handler cannot return them.
104
111
  - The policy runs only on the server. Client-side codec failures stay `SchemaError`.
@@ -113,6 +120,7 @@ const renames: "renameUser" = contracts["users.renameUser"].name;
113
120
  - `Property 'x' is missing in type` at `implement`: the record lacks a handler for action `x`.
114
121
  - Handler compiles but returns an error not in `errors`: type error on the handler's error channel. Declare it on the action or the group.
115
122
  - `Expected 1 arguments, but got 2` at `implement`: the second options object is gone. Move `before` to the adapter that serves the group.
116
- - `map` is not typed from `errors` when declared as a standalone constant: annotate its parameter as `HttpApiError.HttpApiSchemaError` (type import from `effect/unstable/httpapi`).
123
+ - `Parameter 'failure' implicitly has an 'any' type` in a standalone policy constant: a `make` that reads the failure is typed only inline. Annotate the parameter as `HttpApiError.HttpApiSchemaError` (type import from `effect/unstable/httpapi`), or annotate the constant as `ActionGroup.SchemaErrorPolicy<typeof Invalid, typeof Internal>`.
124
+ - `Missing handlers for group "<group>": <actions>` thrown at `implement`, or failing the layer build: the handler record has no own-property function for those actions. Add them to the record itself, not to a prototype.
117
125
  - A service is resolved once and shared across requests when it should be per request: it was yielded in the builder. Move the `yield*` into the handler.
118
126
  - `Duplicate contract group` thrown by `contracts`: two groups share a name, so their keys would collide. Rename one.
@@ -13,6 +13,7 @@ Import `@gjermundgaraba/effect-actions/ActionHttp`.
13
13
  | `Http.groups` | The exact bound contracts, in declaration order. |
14
14
  | `Http.api` | Native Effect `HttpApi` for clients and OpenAPI. |
15
15
  | `Http.layer(apps, options?)` | Serve a readonly collection of implementations; omit options when no hook is needed. |
16
+ | `Http.openApi(path?)` | Serve the OpenAPI document with `GET path`; defaults to `<apiPath>/openapi.json`. |
16
17
 
17
18
  Exported types: `Options`, `LayerOptions`, `Http`, `Api`.
18
19
 
@@ -22,9 +23,8 @@ Exported types: `Options`, `LayerOptions`, `Http`, `Api`.
22
23
  | `make`: `errors` | Surface error codecs declared on every endpoint; defaults to none. |
23
24
  | `layer`: `before` | Effectful hook receiving the selected `Action.Any`, after successful input decoding and before its handler. Failures must belong to the binding's `errors`. |
24
25
 
25
- Layer failures and startup requirements come from the supplied implementations that actually
26
- serve HTTP actions. Served handlers' and the hook's request services remain router request
27
- requirements; router/platform services are also required. No request identity is supplied at startup.
26
+ Layer failures and startup requirements come from the supplied implementations. Every
27
+ handler's and the hook's request services remain router request requirements; router/platform services are also required. No request identity is supplied at startup.
28
28
 
29
29
  Route shape: `POST <apiPath>/<group>/<action>`. Operation ID: `<group>.<action>`.
30
30
 
@@ -32,8 +32,7 @@ Route shape: `POST <apiPath>/<group>/<action>`. Operation ID: `<group>.<action>`
32
32
 
33
33
  ```ts
34
34
  import { Layer } from "effect";
35
- import { HttpRouter, HttpServerResponse } from "effect/unstable/http";
36
- import { HttpApiScalar, HttpApiSwagger, OpenApi } from "effect/unstable/httpapi";
35
+ import { HttpApiScalar, HttpApiSwagger } from "effect/unstable/httpapi";
37
36
  import * as ActionHttp from "@gjermundgaraba/effect-actions/ActionHttp";
38
37
  import { PublicActions, UserActions } from "./contracts.js";
39
38
  import { PublicApp, UserApp } from "./handlers.js";
@@ -56,9 +55,9 @@ const routes = Layer.mergeAll(
56
55
  Http.layer([UserApp], { before: authorize }).pipe(Layer.provide(authentication.layer)),
57
56
  );
58
57
 
59
- // Documents are Effect's own, reading the same contract.
58
+ // Documents are Effect's own, reading the same contract: `GET /api/actions/openapi.json`.
60
59
  const documentation = Layer.mergeAll(
61
- HttpRouter.add("GET", "/openapi.json", HttpServerResponse.jsonUnsafe(OpenApi.fromApi(Http.api))),
60
+ Http.openApi(),
62
61
  HttpApiSwagger.layer(Http.api, { path: "/docs" }),
63
62
  HttpApiScalar.layer(Http.api, { path: "/reference" }),
64
63
  );
@@ -70,7 +69,8 @@ Serve with `HttpRouter.serve(layer).pipe(Layer.provide(NodeHttpServer.layer(crea
70
69
 
71
70
  ### Client
72
71
 
73
- The client is Effect's native grouped `HttpApiClient` over `Http.api`:
72
+ The client is Effect's native grouped `HttpApiClient` over `Http.api`. Code that does not
73
+ run Effects uses the Promise client in [ActionHttpClient.md](ActionHttpClient.md).
74
74
 
75
75
  ```ts
76
76
  import { HttpApiClient } from "effect/unstable/httpapi";
@@ -87,31 +87,33 @@ export const greeting = Effect.gen(function* () {
87
87
 
88
88
  ## Rules
89
89
 
90
+ - HTTP serves every action of every group passed to `make`; an action has no HTTP switch. To keep an action off HTTP, put it in a group left out of `make` and serve that group elsewhere (MCP, Toolkit, CLI).
90
91
  - `apiPath` has no default. Group names must be unique within one `make`. Action names need only be unique within their group; equal action names in different groups do not collide.
91
92
  - `errors` declares the failures the surface around these endpoints answers with rather than a handler: authentication, authorization, rate limiting, upstream unavailability. They are added to every endpoint's error schemas, so `HttpApiClient`, `ActionCliClient` and the in-memory `Testing.httpClient` decode them as typed failures, and they appear in OpenAPI on every operation. A schema an action already declares is not repeated.
92
93
  - Schemas reachable from one endpoint must have distinct `_tag`s: the client decodes a response by trying the schemas declared for its status, and two errors may share a status. Effect unions them per status.
93
94
  - `errors` changes only what is declared. Nothing produces them: the middleware that renders those responses must encode a body that matches the schema, or the client sees a decode error again. Handlers cannot fail with them.
94
- - `Http.layer(apps, options?)` requires each implementation to reference the exact group object passed to `make`; reconstructing an equal-looking group is not sufficient. Each group may occur only once per call. Only supplied implementations are mounted, and a group with no HTTP-enabled actions is not built. Options are optional.
95
+ - `Http.layer(apps, options?)` requires each implementation to reference the exact group object passed to `make`; reconstructing an equal-looking group is not sufficient. Each group may occur only once per call. Only supplied implementations are mounted, and a group without actions is not built. Options are optional.
95
96
  - `before` runs after successful native input decoding and before the selected handler. Invalid input skips the hook and handler. A refusal uses the binding's declared error schema and `httpApiStatus`; its services join handler request requirements. Admission that must precede decoding belongs in outer native HTTP middleware.
96
97
  - Middleware and the hook are per layer call. Groups that need different middleware or a different policy go in separate `Http.layer` calls, merged with `Layer.mergeAll`.
97
98
  - `ActionHttp` sets no response headers of its own. The host owns cache policy; `Authentication.middleware` marks its responses `cache-control: no-store`.
98
99
  - A hook refusal and a handler error are plain declared errors: a JSON body and a status, no other headers. Challenge headers such as `WWW-Authenticate` belong to the admission middleware that runs before the router reaches these routes (see [Authentication.md](Authentication.md)), which sets them on its own response.
99
100
  - Request-time handler services are `HttpRouter.Request.From<"Requires", R>`. Supply them with router middleware (`Authentication.middleware`, `HttpRouter.middleware`), `HttpRouter.provideRequest`, or the request context. Build-time services are ordinary layer requirements.
100
101
  - `Http.api` is a plain `HttpApi`. Anything Effect can do with an `HttpApi` works: `OpenApi.fromApi`, `HttpApiSwagger.layer`, `HttpApiScalar.layer`, `HttpApi.addHttpApi` to combine with other APIs, `HttpApiClient.make`.
102
+ - `Http.openApi(path?)` is `OpenApi.fromApi(Http.api)` as one `GET` route, `<apiPath>/openapi.json` unless a path is given. It documents every bound group, not only the served ones. It is a plain route: middleware provided to its layer covers it, and nothing covers it otherwise.
101
103
  - Client calls always take `{ payload }`. No-input actions take `{ payload: {} }`. Pass `null` or `undefined` only when the codec accepts it. There is no flat client.
102
- - Client effects fail with the declared errors, the group's policy errors, the binding's `errors`, `SchemaError` for local codec failures, and native `HttpClientError`. MCP-only actions are absent from the client.
104
+ - Client effects fail with the declared errors, the group's policy errors, the binding's `errors`, `SchemaError` for local codec failures, and native `HttpClientError`.
103
105
  - Add authentication headers with the native `transformClient` option. Use `HttpApiClient.makeWith` for custom error or service channels. Native per-call response modes are available.
104
106
  - Wire format without a policy: input failure is an empty 400, success is the encoded body, a declared error is its JSON encoding with its `httpApiStatus`, an encoding failure is an empty 400, a defect is an empty 500. Full table in [guarantees.md](guarantees.md).
105
107
  - Each handler runs in a span named `<group>.<action>`, a child of the request span, attributed with `action.group`, `action.name` and `action.access`; its log lines carry the same annotations. The hook, decoding and encoding are outside it, in the request span.
106
108
 
107
109
  ## Failure modes
108
110
 
109
- - Route returns 404: the implementation was never passed to `Http.layer`, or the action has `http: false`, or the path lacks the group segment.
111
+ - Route returns 404: the implementation was never passed to `Http.layer`, or its group is not bound by `make`, or the path lacks the group segment.
110
112
  - Type error listing `HttpRouter.Request.From<"Requires", CurrentActor>` as unsatisfied: a handler yields a request service and no middleware provides it. Wrap that `Http.layer` call with the middleware's `.layer`.
111
113
  - Two groups share a name: `make` throws. Rename one.
112
114
  - `Implementation of group "x" is not served by this adapter`: `Http.layer` received an implementation whose group was not passed to `ActionHttp.make`. Implement the exact shared group object bound by `make`, or add a genuinely new group to the binding. Matching names and schemas do not establish identity.
113
115
  - `Duplicate implementation group: <name>`: a single `Http.layer` call received more than one implementation of the same group. Pass one implementation per group.
114
- - Client method missing for an action: the action is `http: false`.
116
+ - Client method missing for an action: its group is not bound by `make`.
115
117
  - Empty 400 on a valid-looking request: input did not decode. Set a `schemaError` policy on the group to get a typed body, and check `Content-Type: application/json`.
116
118
  - 415: wrong or missing content type.
117
119
  - `HttpClientError: Decode error (401 POST ...)` from a typed client: the surface answered with a status no endpoint declares. Add that error schema to `ActionHttp.make`'s `errors`.
@@ -0,0 +1,80 @@
1
+ # ActionHttpClient
2
+
3
+ A Promise client for an HTTP binding, for code that does not run Effects, such as a browser
4
+ page. It is Effect's native `HttpApiClient` over `fetch`, built once; each call is one request.
5
+
6
+ ## API
7
+
8
+ Import `@gjermundgaraba/effect-actions/ActionHttpClient`.
9
+
10
+ | API | Purpose |
11
+ | ------------------------- | --------------------------------------------------------------------- |
12
+ | `promise(http, options?)` | `client.<group>.<action>(input)` for every action of the binding. |
13
+ | `Options` | Where and how requests are sent. |
14
+ | `Client`, `Method` | The client's type, derived from the binding, and one action's method. |
15
+
16
+ The options are the native `HttpApiClient.make` options except `transformResponse`, plus `fetch`.
17
+ `transformResponse` may change a call's success, failure or required services, which neither
18
+ the method types nor a Promise can follow; wrap `fetch` or use `transformClient` instead.
19
+
20
+ | Option | Meaning |
21
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------- |
22
+ | `baseUrl` | What routes are resolved against, such as `https://api.example.com`. Omitted: relative routes (the page's origin in a browser). |
23
+ | `transformClient` | Wraps the native `HttpClient`. A bearer token: `HttpClient.mapRequest(HttpClientRequest.bearerToken(token))`. |
24
+ | `fetch` | The transport. Defaults to the global `fetch`, looked up on each call. |
25
+
26
+ A method takes the action's decoded input and resolves with its decoded success. An action
27
+ whose input may be empty (no `input`, or only optional fields) may be called without an argument.
28
+
29
+ ## Canonical
30
+
31
+ ```ts
32
+ import { HttpClient, HttpClientError, HttpClientRequest } from "effect/unstable/http";
33
+ import * as ActionHttpClient from "@gjermundgaraba/effect-actions/ActionHttpClient";
34
+ import { Http, UserNotFound } from "./contracts.js";
35
+
36
+ // Promises in, Promises out: for code that does not run Effects, such as a browser page.
37
+ // The options are the native `HttpApiClient.make` options plus `fetch`; a bearer token is
38
+ // a `transformClient`.
39
+ const client = ActionHttpClient.promise(Http, {
40
+ baseUrl: "http://127.0.0.1:3000",
41
+ transformClient: HttpClient.mapRequest(HttpClientRequest.bearerToken("alice")),
42
+ });
43
+
44
+ export const userName = async (id: string): Promise<string> => {
45
+ try {
46
+ return (await client.users.getUser({ id })).name;
47
+ } catch (error) {
48
+ // A declared error rejects as its own value...
49
+ if (error instanceof UserNotFound) return "(no such user)";
50
+
51
+ // ...and what the contract cannot account for as Effect's own `HttpClientError`.
52
+ if (HttpClientError.isHttpClientError(error) && error.response === undefined) {
53
+ return "(server unreachable)";
54
+ }
55
+
56
+ throw error;
57
+ }
58
+ };
59
+ ```
60
+
61
+ Other headers also go through `transformClient` (`HttpClient.mapRequest(HttpClientRequest.setHeader("x-agent", agent))`).
62
+ Reacting to a response every call may meet (a proxy's 401), or a token read per call, goes through
63
+ `fetch`: `fetch: (input, init) => { const request = new Request(input, init); request.headers.set("authorization", "Bearer " + readToken()); return fetch(request); }`.
64
+
65
+ ## Rules
66
+
67
+ - A call rejects with exactly what the native client's Effect fails with. Declared errors arrive as their decoded values: the action's own (its group's `errors` included), its group's schema-error policy's, and the binding's surface `errors`. Classify them with `instanceof`, their `_tag`, or `Schema.is`.
68
+ - Anything the contract does not account for rejects with Effect's own error. `HttpClientError`: the server could not be reached (`response` is `undefined`), or answered with a status no schema declares, or with a body that could not be read. `SchemaError`: the input did not encode, or the success body did not decode.
69
+ - The library adds no error type of its own and interprets no status. Which failures mean "signed out" or "try again" is the caller's decision.
70
+ - Nothing is retried. A rejected write may or may not have happened; only a declared error says what the server did.
71
+ - Every action of a bound group has a method. A group without actions has no namespace.
72
+ - The client holds no connections or timers. Making one is synchronous and sends nothing.
73
+ - A method is not an Effect. Code that runs Effects uses `HttpApiClient.make(Http.api)` directly (see [ActionHttp.md](ActionHttp.md)); its methods take `{ payload }`.
74
+
75
+ ## Failure modes
76
+
77
+ - Rejects with `HttpClientError` whose `reason._tag` is `StatusCodeError` for a 401 or 403: the surface answered with an error the binding does not declare. Add it to `ActionHttp.make`'s `errors`, and have the middleware encode it.
78
+ - Rejects with `HttpClientError` whose `reason._tag` is `InvalidUrlError` outside a browser: `baseUrl` is omitted, and there is no page to resolve relative routes against. Set `baseUrl`.
79
+ - A stubbed global `fetch` is not used: `fetch` was passed as an option, which takes precedence.
80
+ - Property does not exist on the client: the action's group is not bound in this `Http`.
package/docs/ActionMcp.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  MCP tools from implementations, on Effect's native `McpServer`. One `Tool` per MCP-enabled
4
4
  action. Two transports: a Streamable HTTP endpoint mounted on the router, or newline-delimited
5
- JSON-RPC on standard I/O for a subprocess.
5
+ JSON-RPC on standard I/O for a subprocess. Both speak MCP 2026-07-28 only.
6
6
 
7
7
  ## API
8
8
 
@@ -14,15 +14,19 @@ Import `@gjermundgaraba/effect-actions/ActionMcp`.
14
14
  | `layerStdio(apps, options)` | Serve implementations over a subprocess's standard I/O. |
15
15
  | `Options`, `StdioOptions` | Configuration for the two transports. |
16
16
 
17
- | Option | Meaning |
18
- | ----------------- | ----------------------------------------------------------------------------------------------------- |
19
- | `name`, `version` | Required native server information. |
20
- | `protocols` | Required nonempty list of native protocol adapters. |
21
- | `path` | Required HTTP endpoint path; HTTP only, no default. |
22
- | `allowedOrigins` | Optional exact Origin allowlist; HTTP only, not CORS configuration. |
23
- | `instructions` | Optional native server instructions. |
24
- | `errors` | Optional surface error codecs, declared on every served tool. |
25
- | `before` | Optional Effectful hook receiving the selected `Action.Any`; fails only with declared surface errors. |
17
+ The options are the native `McpServer.layerHttp` / `McpServer.layerStdio` options, except
18
+ `protocols`, plus this surface's `errors` and `before`. The native ones pass through unchanged.
19
+
20
+ | Option | Meaning |
21
+ | ------------------------------------ | ----------------------------------------------------------------------------------------------------- |
22
+ | `name`, `version` | Required native server information. |
23
+ | `description`, `websiteUrl`, `icons` | Optional native server information, sent to clients with `name` and `version`. |
24
+ | `instructions` | Optional native server instructions. |
25
+ | `extensions` | Optional native server capability extensions. |
26
+ | `path` | Required HTTP endpoint path; HTTP only, no default. |
27
+ | `allowedOrigins` | Optional exact Origin allowlist; HTTP only, not CORS configuration. |
28
+ | `errors` | Optional surface error codecs, declared on every served tool. |
29
+ | `before` | Optional Effectful hook receiving the selected `Action.Any`; fails only with declared surface errors. |
26
30
 
27
31
  Both layers retain served implementations' build failures and requirements, plus native
28
32
  `IllegalArgumentError`. HTTP needs the router and wraps handler/hook services as request
@@ -33,7 +37,6 @@ is supplied by the server, not owed by the host.
33
37
 
34
38
  ```ts
35
39
  import { Layer } from "effect";
36
- import { McpProtocol } from "effect/unstable/ai";
37
40
  import * as ActionMcp from "@gjermundgaraba/effect-actions/ActionMcp";
38
41
  import { AuditApp, PublicApp, UserApp } from "./handlers.js";
39
42
  import { authentication, authorize, Forbidden } from "./auth.js";
@@ -43,7 +46,6 @@ const allowedOrigins = ["http://localhost:3000"];
43
46
  // One endpoint is one route: its middleware covers every tool on it.
44
47
  // Tools with different middleware needs get their own endpoint.
45
48
  const publicMcp = ActionMcp.layerHttp([PublicApp], {
46
- protocols: [McpProtocol.v2026_07_28],
47
49
  name: "app-public",
48
50
  version: "1.0.0",
49
51
  path: "/mcp/public",
@@ -51,7 +53,6 @@ const publicMcp = ActionMcp.layerHttp([PublicApp], {
51
53
  });
52
54
 
53
55
  const mcp = ActionMcp.layerHttp([UserApp, AuditApp], {
54
- protocols: [McpProtocol.v2026_07_28],
55
56
  name: "app",
56
57
  version: "1.0.0",
57
58
  path: "/mcp",
@@ -73,7 +74,6 @@ choose its policy for every route it covers.
73
74
 
74
75
  ```ts
75
76
  import { Effect, Layer } from "effect";
76
- import { McpProtocol } from "effect/unstable/ai";
77
77
  import { HttpRouter } from "effect/unstable/http";
78
78
  import * as ActionMcp from "@gjermundgaraba/effect-actions/ActionMcp";
79
79
  import { Actions } from "./quickstart.js";
@@ -86,7 +86,6 @@ const mcp = ActionMcp.layerHttp([app], {
86
86
  name: "greetings",
87
87
  version: "1.0.0",
88
88
  path: "/mcp",
89
- protocols: [McpProtocol.v2026_07_28],
90
89
  allowedOrigins,
91
90
  });
92
91
 
@@ -114,7 +113,6 @@ export const routes = Layer.mergeAll(
114
113
  ```ts
115
114
  import { NodeRuntime, NodeStdio } from "@effect/platform-node";
116
115
  import { Console, Effect, Layer, Logger, Schema } from "effect";
117
- import { McpProtocol } from "effect/unstable/ai";
118
116
  import * as Action from "@gjermundgaraba/effect-actions/Action";
119
117
  import * as ActionGroup from "@gjermundgaraba/effect-actions/ActionGroup";
120
118
  import * as ActionMcp from "@gjermundgaraba/effect-actions/ActionMcp";
@@ -132,7 +130,6 @@ const app = ActionGroup.make({ name: "stdio" }, Status).implement({
132
130
  const layer = ActionMcp.layerStdio([app], {
133
131
  name: "effect-actions-stdio",
134
132
  version: "0.1.0",
135
- protocols: [McpProtocol.v2026_07_28],
136
133
  }).pipe(Layer.provide(NodeStdio.layer));
137
134
 
138
135
  // Protocol messages use stdout exclusively. Runtime diagnostics remain on stderr.
@@ -145,18 +142,18 @@ Layer.launch(layer).pipe(
145
142
 
146
143
  ## Rules
147
144
 
148
- - `protocols` is required and must be a nonempty list of Effect's native `McpProtocol.ProtocolAdapter` values. Effect owns negotiation, revision rejection, and sessions. `[McpProtocol.v2026_07_28]` gives a stateless endpoint that needs no initialize handshake.
145
+ - Both transports serve MCP 2026-07-28 and no other revision; there is no `protocols` option. Over HTTP the endpoint is stateless: no initialize handshake, no session, and every request stands alone. Effect owns version checks and rejects any other revision. Stdio has no sessions, so it could serve an older host, but it refuses one deliberately, for uniformity: a client that works over one transport works over the other.
149
146
  - `path` has no default. `layerHttp` uses the single-endpoint Streamable HTTP transport, never the two-endpoint HTTP+SSE form, whatever revision is negotiated.
150
147
  - Requests reaching the native MCP handler with an `Origin` header receive **403** unless that exact origin is listed in `allowedOrigins`. Requests without `Origin` pass this check. Authentication middleware wrapping the endpoint runs first and may reject the request before native Origin validation; the allowlist does not protect authentication from untrusted-origin requests.
151
148
  - `allowedOrigins` is an Origin allowlist, not CORS configuration. Cross-origin browser clients also need outer CORS middleware or a proxy to handle preflight and add response headers. Without it, an allowed-origin `OPTIONS` request receives **405** and even a successful `POST` has no `Access-Control-Allow-Origin`. Keep preflight outside authentication and apply CORS headers to refusals too.
152
149
  - An endpoint is one route. Middleware provided to `layerHttp` covers all of its tools. To serve tools under different middleware, mount them on different paths with separate `layerHttp` calls.
153
- - Only MCP-enabled actions become tools, under `mcp.name` with the resolved hints. A group with no tools is not built.
150
+ - Only MCP-enabled actions become tools, under `mcp.name` with the resolved hints. A group with no tools is not built. The layer's types drop an action's requirements only when its type is certainly hidden (a literal `mcp: false`, see [Action.md](Action.md)); an `mcp` that may be `false` at runtime keeps them.
154
151
  - Every MCP-enabled action must have object-root input; the native server refuses anything else when the layer is built. Omit `input` for a tool with no arguments.
155
152
  - Success is `structuredContent: { value: <encoded success> }`. A declared error is an `isError` result whose text content is the error's JSON encoding, the same bytes HTTP sends as the body, and no `structuredContent`.
156
153
  - Invalid arguments and unencodable results are answered by the native `McpServer`: an `isError` result with a message for the model. Group `schemaError` policies do not apply.
157
154
  - Defects and encoding failures produce the generic `isError` text `Tool execution failed due to an internal server error.`; the cause is logged, not sent.
158
155
  - Tool discovery is not filtered by actor. Every caller sees every tool of the endpoint. Authorization happens in `before`.
159
- - Cancellation is Effect's native RPC interruption.
156
+ - Cancellation is Effect's native RPC interruption. Over HTTP there is no session, so `notifications/cancelled` interrupts nothing; a tool call ends with its HTTP request, whose lifetime (for example, whether a client disconnect interrupts it) is the host's.
160
157
  - Handlers may yield `McpSchema.McpRequestContext` for the client's declared information; the native server supplies it to every tool call, so it is never a router or host requirement.
161
158
  - stdio: the host supplies `Stdio` (`NodeStdio.layer`) and any request-time services explicitly, including the trusted principal. There is no authentication middleware. Tool arguments never establish identity. Keep stdout for protocol messages only and route logs to stderr.
162
159
  - Each endpoint or subprocess owns a fresh native tool registry. That isolates tool names, not application context.
@@ -170,9 +167,9 @@ Layer.launch(layer).pipe(
170
167
  - Type error listing `HttpRouter.Request.From<"Requires", ...>`: a handler yields a request service and the endpoint has no middleware providing it. Provide it with `Layer.provide(middleware.layer)` on that `layerHttp`.
171
168
  - Public tool requires a token: it shares an endpoint with protected tools. Give it its own path.
172
169
  - Client reports a broken transport from a stdio subprocess: something printed to stdout. Set `Logger.LogToStderr` and remove `console.log`.
173
- - Older MCP client cannot connect: the client expects a revision not listed in `protocols`. Add the adapter for that revision.
170
+ - Older MCP client cannot connect: over HTTP a request answers `400` with JSON-RPC error `-32020`, over stdio `initialize` answers JSON-RPC error `-32022`. The client speaks a 2025 revision, which opens with `initialize`. Only 2026-07-28 is served; pin the client to it (the official client: `versionNegotiation: { mode: { pin: "2026-07-28" } }`).
174
171
  - An Origin-bearing request reaches the native handler and gets an empty 403: its `Origin` is not in `allowedOrigins`. Add the exact origin only if the deployment trusts it.
175
172
  - A disallowed Origin receives 401 instead: wrapping authentication rejected it before the native Origin check. Put any required pre-authentication Host/Origin policy in outer host middleware.
176
173
  - Browser calls fail despite an allowed Origin: configure CORS outside authentication and the MCP handler (see the browser example above). The native allowlist alone neither handles preflight nor adds CORS response headers.
177
- - Type error on an empty `protocols` array: provide at least one native protocol adapter.
174
+ - `Object literal may only specify known properties, and 'protocols'`: the revision is fixed. Delete the option.
178
175
  - A refusal arrives as a generic internal-error result: the hook failed with an error this transport does not declare, which is a defect. Add its schema to `errors`.
@@ -51,7 +51,7 @@ With a model: pass `binding.toolkit` as `toolkit` to `LanguageModel.generateText
51
51
 
52
52
  ## Rules
53
53
 
54
- - Selects MCP-enabled actions only, named by `mcp.name`, with resolved hints. Groups with no selected tools are not built. `make(apps, options?)` accepts a readonly implementation collection; options may be omitted.
54
+ - Selects MCP-enabled actions only, named by `mcp.name`, with resolved hints. Groups with no selected tools are not built. The toolkit's type follows `ActionMcp`'s rule: only an action whose `mcp` type is exactly `false` has no tool; one whose `mcp` may be `false` at runtime is typed as a tool with its handler's requirements. `make(apps, options?)` accepts a readonly implementation collection; options may be omitted.
55
55
  - Successes are the action's native values. There is no `{ value }` wrapper. Declared failures are returned as native tool results (`failureMode: "return"`), not raised.
56
56
  - `tools.handle(name, encodedInput)` takes encoded arguments and returns an Effect producing a result stream. The handler starts while that stream is constructed, so request services must be provided around the entire `handle(...).pipe(Effect.flatMap(Stream.runCollect))`, not only around the stream.
57
57
  - `binding.layer` acquires each implementation once, in the layer's scope. Build-time requirements belong to the whole selected implementation.
package/docs/CONTEXT.md CHANGED
@@ -5,7 +5,7 @@ use these words with these meanings.
5
5
 
6
6
  ## Terms
7
7
 
8
- - **Action**: one contract. A name, a description, an input schema, a success schema, declared error schemas, authorization metadata (`access`), and transport metadata (`http`, `mcp`). Holds no behavior. Made by `Action.make`.
8
+ - **Action**: one contract. A name, a description, an input schema, a success schema, declared error schemas, authorization metadata (`access`), and MCP metadata (`mcp`). Holds no behavior. Made by `Action.make`.
9
9
  - **Access**: `"read"` or `"write"`, required on every action and kept as a literal. States what the action does to its resource. Authorization metadata read by a pre-handler hook, independent of the MCP `readOnly` hint, which defaults from it.
10
10
  - **Group**: a named, ordered set of actions plus group-level errors and an optional schema-error policy. Adapters serve groups, clients are organized by group, and the group name is the OpenAPI tag. Made by `ActionGroup.make`.
11
11
  - **Contract**: an action or a group. Pure data; safe to import anywhere, including browsers.
@@ -19,13 +19,13 @@ use these words with these meanings.
19
19
  - **Binding**: the value an adapter returns before anything runs. `ActionHttp.make` returns the HTTP binding (`groups`, `api`, `layer`); `ActionToolkit.make` returns the Toolkit binding (`toolkit`, `layer`).
20
20
  - **Contract map**: the record `ActionGroup.contracts` returns, keyed `<group>.<action>`, with each action's exact type. The shared identity of an action across routes, tools and commands.
21
21
  - **Declared error**: an error schema listed on an action or inherited from its group. Handlers may fail with it. HTTP encodes it with its `httpApiStatus`; MCP returns encoded error text in an `isError` result. Toolkit returns a native failure result, and CLI fails its command Effect without serializing the error.
22
- - **Schema-error policy**: a group option mapping Effect's `HttpApiSchemaError` (decode or encode failure) to a declared policy error with a status. HTTP only.
22
+ - **Schema-error policy**: a group option answering Effect's `HttpApiSchemaError` with a declared policy error and its status: `invalid` when the request did not decode, `internal` when the handler's result did not encode. The library decides which applies. HTTP only.
23
23
  - **Policy error**: an error a schema-error policy may answer with. Part of the transport contract, never returnable by a handler.
24
24
  - **Surface error**: an error declared on an adapter binding rather than on an action. Produced by middleware around the surface or by its pre-handler hook, never by a handler; declared so typed callers decode it.
25
- - **Local-only action**: `http: false` and `mcp: false`. Reachable through `ActionCli` and listed in the catalog.
26
25
  - **Tool**: the MCP or Toolkit projection of an MCP-enabled action, named by `mcp.name` and carrying its hints.
27
26
  - **Endpoint**: one `ActionMcp.layerHttp` mount. One route, one middleware set, one tool registry.
28
- - **Document**: the OpenAPI output of `Http.api`, produced by Effect (`OpenApi.fromApi`).
27
+ - **Document**: the OpenAPI output of `Http.api`, produced by Effect (`OpenApi.fromApi`) and served by `Http.openApi`.
28
+ - **Promise client**: `ActionHttpClient.promise(Http)`, the native `HttpApiClient` as one Promise method per action of the binding, for code that does not run Effects. It rejects with what the native client fails with.
29
29
  - **Catalog**: the offline JSON description of groups produced by `ActionCatalog.make`, with standalone JSON Schemas for encoded values. Descriptive only.
30
30
  - **Identity**: the per-request principal, provided by `Authentication.middleware` under an application-owned tag. Never provided at startup.
31
31
 
package/docs/README.md CHANGED
@@ -9,29 +9,30 @@ Read the card for a module before writing code that uses it. Exported TypeScript
9
9
  Package facts that apply everywhere:
10
10
 
11
11
  - Every module is a subpath import: `import * as Action from "@gjermundgaraba/effect-actions/Action"`. There is no package root.
12
- - The `effect` peer is pinned to an exact release candidate (`4.0.0-rc.116`). Install the same version.
12
+ - The `effect` peer accepts any 4.0 release candidate from `4.0.0-rc.116` on (`>=4.0.0-rc.116 <4.0.0`). The package is built and tested against `4.0.0-rc.117`.
13
13
  - Contracts are pure values. Nothing runs, binds, or acquires services until an adapter layer is built.
14
14
 
15
15
  ## Pages
16
16
 
17
- | Read | When you need to |
18
- | ---------------------------------------- | -------------------------------------------------------------------------------------- |
19
- | [setup.md](setup.md) | install, pin versions, pick entry points, know what the package does not do |
20
- | [Action.md](Action.md) | define one contract: input, success, errors, read/write access, HTTP and MCP flags |
21
- | [ActionGroup.md](ActionGroup.md) | group contracts, declare shared errors, bind handlers, map every contract by name |
22
- | [ActionHttp.md](ActionHttp.md) | serve JSON POST routes, declare surface errors and one hook, publish OpenAPI, call it |
23
- | [ActionMcp.md](ActionMcp.md) | serve MCP tools over Streamable HTTP or stdio |
24
- | [ActionToolkit.md](ActionToolkit.md) | use actions as a native Effect AI `Toolkit` without a server |
25
- | [ActionCli.md](ActionCli.md) | run handlers in-process from a terminal command |
26
- | [ActionCliClient.md](ActionCliClient.md) | call the HTTP API from a terminal command |
27
- | [ActionCatalog.md](ActionCatalog.md) | export contracts as an offline JSON document |
28
- | [Authentication.md](Authentication.md) | provide a per-request identity, publish RFC 9728 discovery, build bearer challenges |
29
- | [Testing.md](Testing.md) | call routes in memory, build MCP requests, drive the official MCP client |
30
- | [guarantees.md](guarantees.md) | cross-cutting rules: dependency lifetimes, wire formats, spans, request context, scope |
17
+ | Read | When you need to |
18
+ | ------------------------------------------ | -------------------------------------------------------------------------------------- |
19
+ | [setup.md](setup.md) | install, pin versions, pick entry points, know what the package does not do |
20
+ | [Action.md](Action.md) | define one contract: input, success, errors, read/write access, HTTP and MCP flags |
21
+ | [ActionGroup.md](ActionGroup.md) | group contracts, declare shared errors, bind handlers, map every contract by name |
22
+ | [ActionHttp.md](ActionHttp.md) | serve JSON POST routes, declare surface errors and one hook, publish OpenAPI, call it |
23
+ | [ActionHttpClient.md](ActionHttpClient.md) | call the HTTP API with Promises, from code that does not run Effects |
24
+ | [ActionMcp.md](ActionMcp.md) | serve MCP 2026-07-28 tools over Streamable HTTP or stdio |
25
+ | [ActionToolkit.md](ActionToolkit.md) | use actions as a native Effect AI `Toolkit` without a server |
26
+ | [ActionCli.md](ActionCli.md) | run handlers in-process from a terminal command |
27
+ | [ActionCliClient.md](ActionCliClient.md) | call the HTTP API from a terminal command |
28
+ | [ActionCatalog.md](ActionCatalog.md) | export contracts as an offline JSON document |
29
+ | [Authentication.md](Authentication.md) | provide a per-request identity, publish RFC 9728 discovery, build bearer challenges |
30
+ | [Testing.md](Testing.md) | call routes and tools in memory, build MCP requests, drive the official MCP client |
31
+ | [guarantees.md](guarantees.md) | cross-cutting rules: dependency lifetimes, wire formats, spans, request context, scope |
31
32
 
32
33
  ## Choose an adapter
33
34
 
34
- - Callers speak JSON over HTTP: `ActionHttp`. Clients use Effect's `HttpApiClient` on `Http.api`.
35
+ - Callers speak JSON over HTTP: `ActionHttp`. Clients use Effect's `HttpApiClient` on `Http.api`, or `ActionHttpClient.promise(Http)` where nothing runs Effects.
35
36
  - Callers are MCP clients: `ActionMcp.layerHttp` for a hosted endpoint, `ActionMcp.layerStdio` for a subprocess.
36
37
  - Callers are an Effect AI program in the same process: `ActionToolkit`.
37
38
  - Callers are humans or scripts in a terminal, handlers run locally: `ActionCli`.
@@ -43,7 +44,6 @@ One implementation (`group.implement(...)`) feeds every adapter.
43
44
  ## Minimal program
44
45
 
45
46
  ```ts
46
- import { McpProtocol } from "effect/unstable/ai";
47
47
  import { Effect, Layer, Schema } from "effect";
48
48
  import * as Action from "@gjermundgaraba/effect-actions/Action";
49
49
  import * as ActionGroup from "@gjermundgaraba/effect-actions/ActionGroup";
@@ -68,7 +68,6 @@ const app = Actions.implement({
68
68
  export const routes = Layer.mergeAll(
69
69
  Http.layer([app]),
70
70
  ActionMcp.layerHttp([app], {
71
- protocols: [McpProtocol.v2026_07_28],
72
71
  name: "greetings",
73
72
  version: "1.0.0",
74
73
  path: "/mcp",
@@ -83,6 +82,7 @@ Serve `routes` with `HttpRouter.serve` and a platform server layer. Result: `POS
83
82
  Repository directory `examples/` ([on GitHub](https://github.com/gjermundgaraba/effect-actions/tree/main/examples)):
84
83
 
85
84
  - `quickstart.ts`, `quickstart-client.ts`: the minimal program and its typed client.
85
+ - `promise-client.ts`: the Promise client, with a declared error and an unreachable server.
86
86
  - `contracts.ts`, `handlers.ts`, `app.ts`, `server.ts`: an authenticated application with three groups, per-group middleware, two MCP endpoints, OpenAPI and Swagger.
87
87
  - `toolkit.ts`, `catalog.ts`, `cli.ts`, `cli-client.ts`, `mcp-stdio.ts`: one file per other projection.
88
88
 
package/docs/Testing.md CHANGED
@@ -12,21 +12,23 @@ Import `@gjermundgaraba/effect-actions/Testing`; official-client helpers are in
12
12
  | -------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
13
13
  | `Testing.httpClient(api, handler, options?)` | Native grouped `HttpApiClient` over an in-memory web handler; retains client middleware requirements. |
14
14
  | `Testing.mcpRequest(options)` | Build a stateless MCP JSON-RPC `Request`. |
15
+ | `Testing.mcpCall(handler, options)` | Call one tool in memory and return its outcome without the wire envelope. |
15
16
  | `TestingClient.withMcpClient(options, run)` | Connect the official client, run an asynchronous callback, then close it. |
16
17
 
17
18
  `httpClient` takes native client options; `baseUrl` defaults to `http://localhost`.
18
19
  Its exported `Handler` type is a web request to response Promise.
19
20
 
20
- | MCP option | Meaning |
21
- | ------------------------------------- | ----------------------------------------------------------------------------------- |
22
- | `mcpRequest`: `url`, `method` | Required destination and JSON-RPC method. |
23
- | `mcpRequest`: `params`, `headers` | Optional parameters and request headers. |
24
- | `withMcpClient`: `fetch`, `path` | Required in-memory request handler and endpoint path. |
25
- | `withMcpClient`: `baseUrl`, `headers` | Optional base URL (default `http://localhost`) and headers. |
26
- | `withMcpClient`: `versionNegotiation` | Optional native client negotiation configuration; omitted means its native default. |
21
+ | MCP option | Meaning |
22
+ | ------------------------------------- | ----------------------------------------------------------- |
23
+ | `mcpRequest`: `url`, `method` | Required destination and JSON-RPC method. |
24
+ | `mcpRequest`: `params`, `headers` | Optional parameters and request headers. |
25
+ | `mcpCall`: `url`, `name` | Required endpoint URL and tool name (`mcp.name`). |
26
+ | `mcpCall`: `arguments`, `headers` | Optional tool arguments (default `{}`) and request headers. |
27
+ | `withMcpClient`: `fetch`, `path` | Required in-memory request handler and endpoint path. |
28
+ | `withMcpClient`: `baseUrl`, `headers` | Optional base URL (default `http://localhost`) and headers. |
27
29
 
28
- Exported option/value types: `McpRequestOptions`, `McpRequestParams`, `McpRequestValue`
29
- from `Testing`, and `McpClientOptions` from `TestingClient`.
30
+ Exported option/value types: `McpRequestOptions`, `McpRequestParams`, `McpRequestValue`,
31
+ `McpCallOptions`, `McpCallResult` from `Testing`, and `McpClientOptions` from `TestingClient`.
30
32
 
31
33
  ## Canonical
32
34
 
@@ -53,13 +55,19 @@ try {
53
55
  Testing.mcpRequest({ url: "http://localhost/mcp", method: "tools/list" }),
54
56
  );
55
57
 
58
+ // One tool call, answered as `{ isError: false, value: "Hello, Ada!" }`.
59
+ const called = await Testing.mcpCall(web.handler, {
60
+ url: "http://localhost/mcp",
61
+ name: "greet",
62
+ arguments: { name: "Ada" },
63
+ });
64
+
56
65
  // The official client uses the same in-memory handler.
57
- const result = await TestingClient.withMcpClient(
58
- { fetch: web.handler, path: "/mcp", versionNegotiation: { mode: { pin: "2026-07-28" } } },
59
- (client) => client.callTool({ name: "greet", arguments: { name: "Ada" } }),
66
+ const result = await TestingClient.withMcpClient({ fetch: web.handler, path: "/mcp" }, (client) =>
67
+ client.callTool({ name: "greet", arguments: { name: "Ada" } }),
60
68
  );
61
69
 
62
- console.log({ greeting, listStatus: listed.status, result });
70
+ console.log({ greeting, listStatus: listed.status, called, result });
63
71
  } finally {
64
72
  await web.dispose();
65
73
  }
@@ -70,14 +78,17 @@ try {
70
78
  - `httpClient` is the same `HttpApiClient` consumers use, with its transport replaced by `handler`. Same `{ payload }` calls, same error channel.
71
79
  - `mcpRequest` pins protocol version 2026-07-28 in both the header and `_meta`. Caller `params._meta` fields override the defaulted client capabilities and info; the merge is shallow. Application metadata is preserved.
72
80
  - `params` accepts what `JSON.stringify` accepts, so tests can send malformed arguments on purpose. `undefined` fields are dropped.
73
- - `withMcpClient` closes the transport in a `finally` block. `versionNegotiation` is passed to the official client unchanged; for a stateless endpoint pin `2026-07-28`.
74
- - Add `Authorization` through `headers` in both MCP helpers, or through `transformClient` in `httpClient` options.
81
+ - `mcpCall` sends one `tools/call` through `mcpRequest` and resolves with `{ isError: false, value }`, the success taken from `structuredContent.value`, or `{ isError: true, error }`, the result's error text parsed as JSON. A declared error or a hook refusal is its JSON encoding, the same body HTTP sends; the native server's own messages (invalid arguments, defects) are not JSON and stay text. It reads a JSON or an event-stream response.
82
+ - `mcpCall` throws when the answer is not a tool result: a status other than 200 (an authentication refusal), or a JSON-RPC error (an unknown tool). Use `mcpRequest` to assert on those responses.
83
+ - `withMcpClient` pins the official client to MCP 2026-07-28, the only revision `ActionMcp` serves, and closes the transport in a `finally` block.
84
+ - Add `Authorization` through `headers` in the MCP helpers, or through `transformClient` in `httpClient` options.
75
85
  - Direct handler tests can use `app.build` under `Effect.scoped`, but they bypass decoding, encoding, and middleware. Keep at least one adapter-level test per transport.
76
86
 
77
87
  ## Failure modes
78
88
 
79
89
  - `@modelcontextprotocol/client` not found: only `TestingClient` needs it. Install the peer in devDependencies, or use `Testing.mcpRequest` instead.
80
- - Official client fails negotiation against a stateless endpoint: set `versionNegotiation: { mode: { pin: "2026-07-28" } }`.
90
+ - `withMcpClient` rejects its options with `versionNegotiation`: the revision is fixed at 2026-07-28. Delete the option.
91
+ - `MCP tools/call "<name>" answered 401`: the call reached authentication without a credential. Pass `headers: { authorization: "Bearer ..." }`.
81
92
  - Handler leaks between tests: `web.dispose()` was not called. Register it with the test runner's cleanup hook.
82
93
  - 404 from `httpClient`: the requested route was not mounted, or the path/base URL is wrong. Include `Http.layer([app])` in the served routes.
83
94
  - Missing platform-service requirements when constructing the web handler: provide `HttpServer.layerServices` to the routes before `toWebHandler`.