@gjermundgaraba/effect-actions 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,10 +76,10 @@ Effect.gen(function* () {
76
76
  ## Install
77
77
 
78
78
  ```sh
79
- pnpm add @gjermundgaraba/effect-actions effect@~4.0.5
79
+ pnpm add @gjermundgaraba/effect-actions effect@~4.1.1
80
80
  ```
81
81
 
82
- It needs TypeScript 7 or newer and is ESM only ([docs/setup.md](docs/setup.md#install)). Add `@effect/platform-node@~4.0.5` to serve or run a CLI from Node, and `@types/node` for its `node:` imports. Every module is a subpath import (`.../Action`, `.../ActionHttp`, ...); there is no package root, so a contracts-only bundle never loads a server.
82
+ It needs TypeScript 7 or newer and is ESM only ([docs/setup.md](docs/setup.md#install)). Add `@effect/platform-node@~4.1.1` to serve or run a CLI from Node, and `@types/node` for its `node:` imports. Every module is a subpath import (`.../Action`, `.../ActionHttp`, ...); there is no package root, so a contracts-only bundle never loads a server.
83
83
 
84
84
  ## Examples
85
85
 
package/dist/Action.mjs CHANGED
@@ -12,9 +12,9 @@ import { inputOf, jsonRoundTrip, onProgressOf, watchInput } from "./contract/cal
12
12
  import { acquireFeeds, eventsOf, feedBuilders } from "./contract/feed.mjs";
13
13
  import { NotServed, SubscriptionError } from "./Event.mjs";
14
14
  import { polledOn, queuedPush, readOn } from "./contract/push.mjs";
15
+ import { Image } from "./contract/media.mjs";
15
16
  import { selectFrom } from "./contract/serving.mjs";
16
17
  import { watching } from "./contract/watch.mjs";
17
- import { Image } from "./contract/media.mjs";
18
18
  import { Idempotency, keyed, layerIdempotency } from "./contract/idempotency.mjs";
19
19
  import { Array as Array$1, Cause, Effect, Function, Layer, Predicate, Schema, Stream as Stream$1 } from "effect";
20
20
  // src/contract/Action.ts
@@ -104,7 +104,7 @@ type WatchServices<C, E extends Any> = [E] extends [never] ? never : C extends E
104
104
  * - Each value an action declaring `progress` reports is one line of compact JSON on stderr, as it arrives, so stdout holds the answer alone; `remoteCommand` asks the server for them too.
105
105
  * - An action answering a stream prints each element on stdout as it arrives, one line of compact JSON, or `render`'s text of it; a declared failure ends the command after the elements before it.
106
106
  * - A declared error is its JSON on stderr, under Effect CLI's `ERROR` heading, the command failing with a `UserError` whose `cause` is the error, exit 1 or its `Runtime.errorExitCode`; a refusal as `Action.Unauthenticated` and `Action.Forbidden` say; input that does not decode, in `--input` or a flag's JSON value, is `InvalidInput`'s JSON there, while a missing flag or a rejected choice is Effect CLI's own parse error.
107
- * - Effect CLI styles what it prints, a failure's JSON included, on a terminal and, from Effect 4.0.6, wherever `FORCE_COLOR` forces colour: for plain text there, set `NO_COLOR` or provide `TerminalCapabilities.TerminalCapabilities` with `canColor: false`.
107
+ * - Effect CLI styles what it prints, a failure's JSON included, on a terminal and wherever `FORCE_COLOR` forces colour: for plain text there, set `NO_COLOR` or provide `TerminalCapabilities.TerminalCapabilities` with `canColor: false`.
108
108
  * - A failure no schema encodes, a builder's or an accepted error that does not encode, is a `UserError` printed as its tag or name and its message, then its causes, never its other fields; a defect, an undeclared failure, or a success that does not encode is the command's defect, which `runMain` reports as `logToStderr` says.
109
109
  * - Provide services with `Command.provide` on the command, built when an action runs: provided around `Command.run`, they are built before parsing, so `--help` and a mistyped flag open the database.
110
110
  * - Each run builds the action's implementation, its builder and an authorizer an Effect builds, and releases them after the call, even where the host already built them; implementations passed beside it are not built.
@@ -94,7 +94,7 @@ const checkedCommandsOf = (commands, actions) => {
94
94
  * - Each value an action declaring `progress` reports is one line of compact JSON on stderr, as it arrives, so stdout holds the answer alone; `remoteCommand` asks the server for them too.
95
95
  * - An action answering a stream prints each element on stdout as it arrives, one line of compact JSON, or `render`'s text of it; a declared failure ends the command after the elements before it.
96
96
  * - A declared error is its JSON on stderr, under Effect CLI's `ERROR` heading, the command failing with a `UserError` whose `cause` is the error, exit 1 or its `Runtime.errorExitCode`; a refusal as `Action.Unauthenticated` and `Action.Forbidden` say; input that does not decode, in `--input` or a flag's JSON value, is `InvalidInput`'s JSON there, while a missing flag or a rejected choice is Effect CLI's own parse error.
97
- * - Effect CLI styles what it prints, a failure's JSON included, on a terminal and, from Effect 4.0.6, wherever `FORCE_COLOR` forces colour: for plain text there, set `NO_COLOR` or provide `TerminalCapabilities.TerminalCapabilities` with `canColor: false`.
97
+ * - Effect CLI styles what it prints, a failure's JSON included, on a terminal and wherever `FORCE_COLOR` forces colour: for plain text there, set `NO_COLOR` or provide `TerminalCapabilities.TerminalCapabilities` with `canColor: false`.
98
98
  * - A failure no schema encodes, a builder's or an accepted error that does not encode, is a `UserError` printed as its tag or name and its message, then its causes, never its other fields; a defect, an undeclared failure, or a success that does not encode is the command's defect, which `runMain` reports as `logToStderr` says.
99
99
  * - Provide services with `Command.provide` on the command, built when an action runs: provided around `Command.run`, they are built before parsing, so `--help` and a mistyped flag open the database.
100
100
  * - Each run builds the action's implementation, its builder and an authorizer an Effect builds, and releases them after the call, even where the host already built them; implementations passed beside it are not built.
@@ -168,7 +168,7 @@ export declare function make<const Contracts extends ReadonlyArray<Any$1 | Any>>
168
168
  * - The 415 keeps from every handler what another site's page can send without a CORS preflight, such as a form post carrying the user's cookie; the server's CORS policy decides the rest.
169
169
  * - Router middleware providing a request service `X` is declared `HttpRouter.middleware<{ provides: X }>()`: without the type argument it runs and the layer still owes `X`.
170
170
  * - `HttpRouter.provideRequest(layer)` builds its layer once, at startup, so it never provides an identity or a tenant.
171
- * - A request body is read whole, however large, unless the host provides `HttpServerRequest.MaxBodySize` to `HttpRouter.serve`, limiting every route that reads its body whole, MCP endpoints included; a body a route reads as a stream is not limited. On Node a request over it is an empty 413 from Effect 4.0.6, and before it gets no response, its connection closed; `HttpRouter.toWebHandler` ignores it, so limit bodies in the platform serving the handler.
171
+ * - A request body is read whole, however large, unless the host provides `HttpServerRequest.MaxBodySize` to `HttpRouter.serve`, limiting every route that reads its body whole, MCP endpoints included; a body a route reads as a stream is not limited. A request over it is an empty 413. Under `HttpRouter.toWebHandler` provide it with `HttpRouter.provideRequest`: `Layer.provide` around the routes limits `ActionHttp`'s and no MCP endpoint.
172
172
  * - An `ErrorReporter` the server runs with is given, as `Info`, a handler's declared failure and an input that does not decode, never a refusal or a refused credential: give an error class `override readonly [ErrorReporter.ignore] = true` to keep it out, and drop `Info` for a built-in error, which takes no mark.
173
173
  * - An event's route takes `{ input, cursor }`, a `cursor` omitted or `null` reading from now, and answers a page, `{ events, cursor, truncated, hasMore, nextPollMs }`, or, to a request accepting `text/event-stream`, an SSE stream of `Checked`, `Occurrence`, `Gap` and `Failed` data, a `Checked` every 30 seconds; the stream carries no `id:`, so `Last-Event-ID` resumes nothing: resume from a cursor in the body.
174
174
  * - A subscription is refused as an action's call is, before its stream starts, with the route's 401 or 403; a refusal later ends the stream with Effect's `effect/http-api/stream/failure` event.
@@ -6,15 +6,16 @@ import { Any as Any$2, Matching, ProviderOf, RemoteRequest, Required, ServerBuil
6
6
  import { McpCallError } from "./mcp/reply.mjs";
7
7
  import { Client, ClientOptions, client } from "./mcp/client.mjs";
8
8
  import { Params, RequestOptions, request } from "./mcp/request.mjs";
9
- import { Cause, Effect, Layer, Stdio } from "effect";
9
+ import { Cause, Effect, Layer, Scope, Stdio } from "effect";
10
10
  import { HttpRouter } from "effect/http";
11
11
  import { McpSchema, McpServer } from "effect/ai";
12
12
  /**
13
- * An MCP server, over HTTP or stdio: every native `McpServer.layerStdio` option but `protocols`,
14
- * the server information, `instructions` and `extensions` among them, the actions `A` that are
15
- * its tools and the event types `A` it serves, and the native features it serves beside them.
13
+ * An MCP server, over HTTP or stdio: every native `McpServer.layerStdio` option but `protocols`
14
+ * and `registrations`, the server information, `instructions`, `extensions` and `cacheHints`
15
+ * among them, the actions `A` that are its tools and the event types `A` it serves, and the
16
+ * native features it serves beside them.
16
17
  */
17
- export interface Options<E = never, R = never, A extends Any$1 | Any = Any$1 | Any> extends Omit<Parameters<typeof McpServer.layerStdio>[0], "protocols"> {
18
+ export interface Options<E = never, R = never, A extends Any$1 | Any = Any$1 | Any> extends Omit<Parameters<typeof McpServer.layerStdio>[0], "protocols" | "registrations"> {
18
19
  /**
19
20
  * The actions that are tools and the event types it serves, among the implementations':
20
21
  * `[GetUser, RenameUser, UserRenamed]`, exactly those. Each keeps its implementation's
@@ -27,24 +28,26 @@ export interface Options<E = never, R = never, A extends Any$1 | Any = Any$1 | A
27
28
  readonly actions?: readonly A[] | undefined;
28
29
  /**
29
30
  * Native MCP features served beside the actions' tools, such as `McpServer.resource`,
30
- * `McpServer.prompt` and `McpServer.toolkit` layers merged into one. They register on this
31
- * server's registry and run with the services they were built with, and no `authorize` runs for
32
- * them.
31
+ * `McpServer.prompt` and `McpServer.toolkit` layers merged into one: Effect's `registrations`,
32
+ * registered on this server's registry before it reads a request. No `authorize` runs for them.
33
33
  *
34
34
  * **Gotchas**
35
35
  *
36
- * - Merged beside the endpoint instead of passed here, they register on another registry and are never served, without an error.
37
- * - A service provided to this layer itself is built again for the features alone, so a resource reads another store than the tools write: provide it around the endpoint.
38
- * - They never receive a request's services, so they cannot read the caller: content that depends on the caller is an action.
36
+ * - Merged beside the endpoint instead of passed here, they need an `McpServer` nothing provides: a type error, and `Service not found: effect/ai/McpServer` as the layer builds.
37
+ * - A service a handler reads is a request's, in the endpoint's `Request<"Requires", X>`, as a tool's is: provide it with router middleware, or around `runStdio`. `Layer.provide` does not satisfy it.
38
+ * - A service known at startup is read in a `Layer.unwrap` around the feature, which closes over it: the endpoint then needs it at startup, and shares it with the tools.
39
+ * - A layer provided to this layer itself is built again for the features alone, so a resource reads another store than the tools write: provide it around the endpoint.
40
+ * - They cannot read the caller, which `authentication` gives protected tools alone: content that depends on the caller is an action.
41
+ * - A `McpServer.middleware` layer merged into them, a `McpServer.visibility` one included, runs for the actions' tools and not for the features beside it: provide it around the endpoint to reach both.
39
42
  */
40
43
  readonly features?: Layer.Layer<never, E, R> | undefined;
41
44
  }
42
45
  /**
43
46
  * One Streamable HTTP MCP endpoint: `Options`, `authentication`, `requestScoped`, and every native
44
- * `McpServer.layerHttp` option, `allowedOrigins` among them, except `protocols` and
45
- * `allowSessionTermination`, which are fixed.
47
+ * `McpServer.layerHttp` option, `allowedOrigins` among them, except `protocols`, `registrations`
48
+ * and `allowSessionTermination`, which are fixed.
46
49
  */
47
- export interface LayerHttpOptions<E = never, R = never, A extends Any$1 | Any = Any$1 | Any> extends Options<E, R, A>, Omit<Parameters<typeof McpServer.layerHttp>[0], "protocols" | "path" | "allowSessionTermination"> {
50
+ export interface LayerHttpOptions<E = never, R = never, A extends Any$1 | Any = Any$1 | Any> extends Options<E, R, A>, Omit<Parameters<typeof McpServer.layerHttp>[0], "protocols" | "path" | "allowSessionTermination" | "registrations"> {
48
51
  /** The endpoint's route; defaults to `/mcp`. */
49
52
  readonly path?: HttpRouter.PathInput;
50
53
  /**
@@ -57,7 +60,8 @@ export interface LayerHttpOptions<E = never, R = never, A extends Any$1 | Any =
57
60
  * **Gotchas**
58
61
  *
59
62
  * - A credential a request presents is still verified, on a public tool's call too: an expired or invalid one answers 401, its challenge naming `invalid_token`, on which a client refreshes it or signs in again.
60
- * - `tools/list` names every tool, protected ones included: serve public tools on an endpoint of their own if signed-out callers must not see the rest.
63
+ * - `tools/list` names every tool, protected ones included: to list only the public ones to a request sending no credential, provide around the endpoint a `McpServer.visibility` returning `false` for a protected tool's `target` when, under Bearer, `headers["authorization"]` is absent, as the endpoint verifies a credential sent before it answers the listing. Or serve public tools on an endpoint of their own.
64
+ * - A client shown no protected tool never calls one, so it never gets the 401 that starts its sign-in: hide them only from clients that sign in before listing, such as one configured with a token.
61
65
  * - A client of a 2025 revision opens a session, which on an endpoint serving a protected tool only a signed-in caller does: it signs in for every request there, a public tool's call and `tools/list` included.
62
66
  * - Every prompt and resource request needs a credential, listings included: to offer them signed out, serve them on an endpoint without protected tools.
63
67
  * - A handler that sends a notification starts the response, so a refusal after it is an `isError: true` tool result, not the 401 or 403 a client re-authorizes on: refuse in `authorize`.
@@ -86,7 +90,8 @@ export interface LayerHttpOptions<E = never, R = never, A extends Any$1 | Any =
86
90
  }
87
91
  type ToolRequestContext<R> = Exclude<R, McpSchema.McpRequestContext | McpServer.McpServer>;
88
92
  type HttpToolRequestContext<R> = Exclude<ToolRequestContext<R>, HttpRouter.Provided>;
89
- type Features<R> = Exclude<R, McpServer.McpServer>;
93
+ type Features<R> = Exclude<McpServer.McpRequest.Without<R>, McpServer.McpServer>;
94
+ type FeatureRequest<R> = McpServer.McpRequest.Only<"Requires", R>;
90
95
  type Contracts<Apps extends Served, O> = SelectedOf<O, Apps> | SelectedEventsOf<O, Apps>;
91
96
  type ServerError<Apps extends Served, O> = BuildError<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventBuildError<HoldingEvents<Member<Apps>, SelectedEventsOf<O, Apps>>, SelectedEventsOf<O, Apps>> | Cause.IllegalArgumentError;
92
97
  type EventServices<Apps extends Served, O> = EventBuildServices<HoldingEvents<Member<Apps>, SelectedEventsOf<O, Apps>>, SelectedEventsOf<O, Apps>>;
@@ -130,7 +135,7 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
130
135
  * - A poll's `maxEvents` caps a log source's page, at most 100, and is not honored for a check source, whose page is answered whole since only its last cursor resumes; `maxAgeMs` is accepted and not honored, a log source keeping what its `log.maxAge` and `log.maxEvents` say.
131
136
  * - A push stream's failure that no refusal explains, such as an upstream's outage, is `notifications/events/error`, its cause logged and reported, and the stream resumes from where it reached after 5 seconds; a refusal ends it with `notifications/events/terminated`. One before `active`, or a poll's, is a JSON-RPC `-32603`, which `client`'s `watch` reconnects after, as after a 5xx.
132
137
  */
133
- export declare function layerHttp<const Apps extends Served, const O extends Selection<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> = {}, E = never, R = never, const D extends Any$2 | undefined = undefined>(implementations: Apps, options: LayerHttpOptions<E, R, ActionOf<Member<Apps>> | EventOf<Member<Apps>>> & O & NoInfer<Known<O, LayerHttpOptions<E, R>>> & NoInfer<Required<Contracts<Apps, O>>> & Matching<NoInfer<Contracts<Apps, O>>, NoInfer<D>> & Inferring<D, NoInfer<Contracts<Apps, O>>>): Layer.Layer<never, ServerError<Apps, O> | E, ServerBuildServices<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventServices<Apps, O> | HttpRouter.HttpRouter | HttpRouter.Request.From<"Requires", HttpToolRequestContext<RemoteRequest<Member<Apps>, SelectedOf<O, Apps>> | EventServedRequest<Member<Apps>, SelectedEventsOf<O, Apps>>>> | ProviderOf<D> | Features<R>>;
138
+ export declare function layerHttp<const Apps extends Served, const O extends Selection<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> = {}, E = never, R = never, const D extends Any$2 | undefined = undefined>(implementations: Apps, options: LayerHttpOptions<E, R, ActionOf<Member<Apps>> | EventOf<Member<Apps>>> & O & NoInfer<Known<O, LayerHttpOptions<E, R>>> & NoInfer<Required<Contracts<Apps, O>>> & Matching<NoInfer<Contracts<Apps, O>>, NoInfer<D>> & Inferring<D, NoInfer<Contracts<Apps, O>>>): Layer.Layer<never, ServerError<Apps, O> | E, ServerBuildServices<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventServices<Apps, O> | HttpRouter.HttpRouter | HttpRouter.Request.From<"Requires", HttpToolRequestContext<RemoteRequest<Member<Apps>, SelectedOf<O, Apps>> | EventServedRequest<Member<Apps>, SelectedEventsOf<O, Apps>> | FeatureRequest<R>>> | ProviderOf<D> | Features<R>>;
134
139
  /**
135
140
  * Serve MCP tools through newline-delimited JSON-RPC on standard I/O, speaking MCP
136
141
  * 2026-07-28, 2025-11-25 or 2025-06-18, as the host negotiates: the whole
@@ -147,5 +152,5 @@ export declare function layerHttp<const Apps extends Served, const O extends Sel
147
152
  * - A line that is not JSON goes unanswered, with no `-32700` as over HTTP, and the lines after it are still answered.
148
153
  * - The layers provided around it log to stdout, among the protocol's lines: apply `ActionCli.logToStderr` to the program, last, as its JSDoc says.
149
154
  */
150
- export declare function runStdio<const Apps extends Served, const O extends Selection<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> = {}, E = never, R = never>(implementations: Apps, options: Options<E, R, ActionOf<Member<Apps>> | EventOf<Member<Apps>>> & O & NoInfer<Known<O, Options<E, R>>>): Effect.Effect<void, ServerError<Apps, O> | E, BuildServices<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventServices<Apps, O> | Stdio.Stdio | ToolRequestContext<ServedRequest<Member<Apps>, SelectedOf<O, Apps>> | EventRequestOf<Member<Apps>, SelectedEventsOf<O, Apps>>> | Features<R>>;
155
+ export declare function runStdio<const Apps extends Served, const O extends Selection<ActionOf<Member<Apps>> | EventOf<Member<Apps>>> = {}, E = never, R = never>(implementations: Apps, options: Options<E, R, ActionOf<Member<Apps>> | EventOf<Member<Apps>>> & O & NoInfer<Known<O, Options<E, R>>>): Effect.Effect<void, ServerError<Apps, O> | E, BuildServices<Holding<Member<Apps>, SelectedOf<O, Apps>>, SelectedOf<O, Apps>> | EventServices<Apps, O> | Stdio.Stdio | ToolRequestContext<ServedRequest<Member<Apps>, SelectedOf<O, Apps>> | EventRequestOf<Member<Apps>, SelectedEventsOf<O, Apps>> | Exclude<FeatureRequest<R>, Scope.Scope>> | Features<R>>;
151
156
  export { type Client, type ClientOptions, McpCallError, type Params, type RequestOptions, client, request };
@@ -5,11 +5,12 @@ import { toolSuccessOf } from "./contract/stream.mjs";
5
5
  import { acquire, answeringWhole } from "./contract/implementation.mjs";
6
6
  import { inputParseOptions } from "./contract/call.mjs";
7
7
  import { hintsOf } from "./contract/hints.mjs";
8
+ import { liftOf, liftedFrom } from "./contract/lift.mjs";
8
9
  import { promote, providerOf } from "./authentication/provider.mjs";
9
10
  import { provideServed, selectFrom } from "./contract/serving.mjs";
10
11
  import { recordStepUp } from "./authentication/refusal.mjs";
11
12
  import { withStderrConsole } from "./stdio/console.mjs";
12
- import { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, liftOf, liftedFrom, protocols, routingFormsOf, toolJsonSchema } from "./mcp/protocol.mjs";
13
+ import { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, protocols, toolJsonSchema } from "./mcp/protocol.mjs";
13
14
  import { eventSchemasOf, refuseUnservable, serveWebhooks, withEvents } from "./mcp/bridge.mjs";
14
15
  import { progressNotifier } from "./mcp/progress.mjs";
15
16
  import { McpCallError } from "./mcp/reply.mjs";
@@ -100,6 +101,7 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
100
101
  yield* registry.addTool({
101
102
  tool,
102
103
  annotations: Context.empty(),
104
+ services: built,
103
105
  handle: (payload) => Effect.annotateCurrentSpan({ tool: action.name }).pipe(Effect.andThen(() => decode(payload ?? {})), Effect.mapError(({ message }) => new McpSchema.InvalidParams({ message: new AiError.ToolParameterValidationError({
104
106
  toolName: action.name,
105
107
  description: message
@@ -109,7 +111,7 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
109
111
  content: nativeJsonTextOf(encoded)
110
112
  })),
111
113
  onSuccess: (success) => Effect.map(encodeSuccess(success), (encoded) => resultOf(encoded, success))
112
- }))), Effect.catchCause(internalErrorOnDefect), Effect.updateContext((request) => Context.merge(built, request)))
114
+ }))), Effect.catchCause(internalErrorOnDefect))
113
115
  });
114
116
  }
115
117
  });
@@ -133,7 +135,7 @@ const server = (apps, serving, transport, features = Layer.empty) => {
133
135
  yield* serveWebhooks(serving);
134
136
  yield* registerTools(apps, authentication);
135
137
  });
136
- return Layer.effectDiscard(register).pipe(Layer.provide(features), Layer.provide(transport), Layer.fresh, provideServed({
138
+ return Layer.empty.pipe(Layer.provide(transport(Layer.effectDiscard(register).pipe(Layer.provide(features)))), Layer.fresh, provideServed({
137
139
  apps,
138
140
  events
139
141
  }));
@@ -149,7 +151,7 @@ const namedMethods = /* @__PURE__ */ new Map([
149
151
  ["events/poll", "event"],
150
152
  ["events/stream", "event"]
151
153
  ]);
152
- const openOf = (contracts) => new Set(contracts.filter(({ caller }) => caller === Anyone).flatMap(({ name }) => routingFormsOf(name)));
154
+ const openOf = (contracts) => new Set(contracts.flatMap(({ name, caller }) => caller === Anyone ? [name] : []));
153
155
  const requiresAuthentication = (actions, events) => {
154
156
  const open = {
155
157
  tool: openOf(actions),
@@ -163,7 +165,8 @@ const requiresAuthentication = (actions, events) => {
163
165
  if (anonymousMethods.has(method)) return false;
164
166
  const named = namedMethods.get(method);
165
167
  if (named === void 0) return true;
166
- const name = headers["mcp-name"];
168
+ const sent = headers["mcp-name"];
169
+ const name = sent === void 0 ? void 0 : McpServer.decodeNameHeader(sent);
167
170
  return name === void 0 || !open[named].has(name);
168
171
  };
169
172
  };
@@ -183,16 +186,18 @@ function layerHttp(apps, { actions, features, path = defaultPath, authentication
183
186
  events,
184
187
  authentication
185
188
  };
186
- const transport = server(selected, serving, requestScoped === true ? McpServer.layerHttpRequestScoped({
189
+ const transport = server(selected, serving, (registrations) => requestScoped === true ? McpServer.layerHttpRequestScoped({
187
190
  ...options,
188
191
  path,
189
- protocols: servingEvents([httpProtocol], serving)
192
+ protocols: servingEvents([httpProtocol], serving),
193
+ registrations
190
194
  }) : McpServer.layerHttp({
191
195
  ...options,
192
196
  path,
193
197
  protocols: servingEvents(protocols, serving),
194
198
  allowSessionTermination: true,
195
- allowSubscriptions: allowSubscriptions ?? (features !== void 0 || events.length > 0)
199
+ allowSubscriptions: allowSubscriptions ?? (features !== void 0 || events.length > 0),
200
+ registrations
196
201
  }), features);
197
202
  if (authentication === void 0) return transport.pipe(Layer.provide(HttpRouter.middleware(readsItsBody).layer));
198
203
  const required = requiresAuthentication(served, listed);
@@ -211,9 +216,10 @@ function runStdio(apps, { actions, features, ...options }) {
211
216
  events,
212
217
  authentication: void 0
213
218
  };
214
- const transport = server(selected, serving, McpServer.layerStdio({
219
+ const transport = server(selected, serving, (registrations) => McpServer.layerStdio({
215
220
  ...options,
216
- protocols: servingEvents(protocols, serving)
221
+ protocols: servingEvents(protocols, serving),
222
+ registrations
217
223
  }).pipe(Layer.provide(jsonLinesOnly)), features);
218
224
  return Layer.launch(transport).pipe(withStderrConsole, Effect.forkChild, Effect.flatMap(Fiber.await), Effect.flatMap((exit) => Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause) ? Effect.failCause(exit.cause) : Effect.void));
219
225
  }
@@ -88,6 +88,9 @@ type ProgressOf<P> = P extends Codec ? Schema.decodeTo<Schema.declare<Reported<P
88
88
  *
89
89
  * - An action answering a stream, `Action.Stream`, answers its elements collected into one array once the stream ends, its tool's success that array.
90
90
  * - An action declaring `progress` streams each value as a result with `preliminary: true` before its success, its `result` `{ _tag: "Progress", value }`, so its tool's success schema is that or `success`; a model reads the success alone.
91
+ * - An image where `Action.Image` lifts one reaches the model as a `file` part of the result's `modelOutput`, after one `text` part of the other fields' JSON when the success has any, while `result` and `encodedResult` keep it: a `Chat`'s history holds each image twice, its bytes and their base64.
92
+ * - A provider that takes only text tool results reads each image as a placeholder, `[image/png omitted]` as `Prompt.toolModelOutputToText` writes it, so its model never sees the image.
93
+ * - `setSuccess(…)` on a generated tool drops the mapping: the model reads the JSON again, the bytes in base64.
91
94
  * - A success is a result with `isFailure: false`, `result` the value and `encodedResult` its JSON; a declared error a result with `isFailure: true` and `result` the error, which the model reads, never a raised failure; a refusal as `Action.Unauthenticated` and `Action.Forbidden` say.
92
95
  * - Arguments that do not decode are a result with `isFailure: true` whose `result` is an `AiError` with `reason` a `ToolParameterValidationError`, never `InvalidInput`, and neither `authorize` nor the handler runs; undeclared arguments are dropped and the call runs.
93
96
  * - A defect, or a failure the action's errors reject, is the call's defect; a success or an error that does not encode fails the call with an `AiError`, `Failed to encode result for tool …`.
@@ -4,8 +4,9 @@ import { progressSink } from "./contract/progress.mjs";
4
4
  import { toolSuccessOf } from "./contract/stream.mjs";
5
5
  import { Implementation, acquire, answeringWhole, provideHandlers, select, toList } from "./contract/implementation.mjs";
6
6
  import { hintsOf } from "./contract/hints.mjs";
7
+ import { liftOf, liftedFrom } from "./contract/lift.mjs";
7
8
  import { Effect, Schema, SchemaGetter } from "effect";
8
- import { Tool, Toolkit } from "effect/ai";
9
+ import { Prompt, Tool, Toolkit } from "effect/ai";
9
10
  // src/toolkit/ActionToolkit.ts
10
11
  const annotateIfGiven = (tool, key, value) => value === void 0 ? tool : tool.annotate(key, value);
11
12
  const annotateFromContract = (tool, action) => {
@@ -28,6 +29,15 @@ const ProgressOf = (progress) => Schema.TaggedStruct("Progress", { value: progre
28
29
  value: reported.value
29
30
  }))
30
31
  }));
32
+ const modelOutputOf = (success) => {
33
+ const lift = liftOf(success);
34
+ if (lift.fields.length === 0) return;
35
+ const encodeRest = lift.rest === void 0 ? void 0 : Schema.encodeUnknownSync(Schema.toCodecJson(lift.rest));
36
+ return (result) => [...encodeRest === void 0 ? [] : [Prompt.textPart({ text: JSON.stringify(encodeRest(result)) })], ...liftedFrom(lift, result).map(({ value }) => Prompt.filePart({
37
+ mediaType: value.mimeType,
38
+ data: value.data
39
+ }))];
40
+ };
31
41
  const jsonToolOf = (action) => {
32
42
  const success = toolSuccessOf(action.success);
33
43
  return Tool.make(action.name, {
@@ -35,7 +45,8 @@ const jsonToolOf = (action) => {
35
45
  parameters: Schema.toCodecJson(action.input),
36
46
  success: Schema.toCodecJson(action.progress === void 0 ? success : Schema.Union([ProgressOf(action.progress), success])),
37
47
  failure: Schema.toCodecJson(Schema.Union(projectedErrors(action))),
38
- failureMode: "return"
48
+ failureMode: "return",
49
+ toModelOutput: modelOutputOf(success)
39
50
  });
40
51
  };
41
52
  function make(apps, options) {
@@ -44,7 +44,9 @@ export interface Options {
44
44
  * - A subscription suspended stays suspended when restored, until its subscriber's refresh delivers again.
45
45
  * - Secrets and identities are kept as JSON, as given, so give the layer a store only the server reads.
46
46
  * - A kept subscription whose input or identity no longer decodes, as after a schema change, is reported at each build and never restored, until its subscriber unsubscribes it.
47
- * - A store whose index cannot be read as the layer builds fails the build; a write that fails later is reported and tried again with the next, and pending writes get 5 seconds when the layer closes.
47
+ * - The build lists every key of the store, a `SELECT id` over a SQL store's whole table or a read of the file store's directory, and restores those under `effect-actions/webhook/`: where the application keeps many keys in that store, give the layer one of its own.
48
+ * - A store whose keys cannot be listed as the layer builds fails the build, as the file store's does on a file name that is not percent-encoding, such as `100%.txt`; a write that fails later is reported and tried again with the next.
49
+ * - Writes still pending 5 seconds into the layer's close are reported as `UnfinishedWrites` and dropped: the next build restores each subscription as last written, missing one subscribed since and keeping one removed since.
48
50
  * - A callback's verification is not kept: a restored subscription delivers on, and a new one to the same callback after a restart is verified again.
49
51
  */
50
52
  readonly persist?: boolean | undefined;
@@ -0,0 +1,80 @@
1
+ import { unsuspended } from "./ast.mjs";
2
+ import { Media, kindOf } from "./media.mjs";
3
+ import { Predicate, Schema, SchemaAST } from "effect";
4
+ // src/contract/lift.ts
5
+ const isMedia = Schema.is(Media);
6
+ const isMediaArray = Schema.is(Schema.Array(Media));
7
+ const kindOfUnsuspended = (ast) => kindOf(unsuspended(ast));
8
+ const wholeSuccessMediaOf = (suspended) => {
9
+ const ast = unsuspended(suspended);
10
+ const one = kindOf(ast);
11
+ if (one !== void 0) return {
12
+ kind: one,
13
+ many: false
14
+ };
15
+ if (!SchemaAST.isArrays(ast) || ast.encoding !== void 0) return;
16
+ const [kind, ...others] = new Set([...ast.elements, ...ast.rest].map(kindOfUnsuspended));
17
+ return kind === void 0 || others.length > 0 ? void 0 : {
18
+ kind,
19
+ many: true
20
+ };
21
+ };
22
+ const mediaFieldOf = (field) => {
23
+ const optional = field.context?.isOptional === true;
24
+ const ast = unsuspended(field);
25
+ if (optional && SchemaAST.isUnion(ast) && ast.types.length === 2) {
26
+ const [definedMember, ...otherDefinedMembers] = ast.types.filter((member) => !SchemaAST.isUndefined(member));
27
+ const kind = definedMember === void 0 || otherDefinedMembers.length > 0 ? void 0 : kindOfUnsuspended(definedMember);
28
+ return kind === void 0 ? void 0 : {
29
+ kind,
30
+ many: false
31
+ };
32
+ }
33
+ const whole = wholeSuccessMediaOf(ast);
34
+ return whole === void 0 || optional && whole.many ? void 0 : whole;
35
+ };
36
+ const liftOf = (success) => {
37
+ const ast = unsuspended(success.ast);
38
+ const whole = wholeSuccessMediaOf(ast);
39
+ if (whole !== void 0) return {
40
+ fields: [{
41
+ name: void 0,
42
+ ...whole
43
+ }],
44
+ rest: void 0
45
+ };
46
+ if (!SchemaAST.isObjects(ast) || ast.encoding !== void 0) return {
47
+ fields: [],
48
+ rest: success
49
+ };
50
+ const fields = ast.propertySignatures.flatMap(({ name, type }) => {
51
+ const field = mediaFieldOf(type);
52
+ return field === void 0 ? [] : [{
53
+ name: String(name),
54
+ ...field
55
+ }];
56
+ });
57
+ if (fields.length === 0) return {
58
+ fields,
59
+ rest: success
60
+ };
61
+ const names = new Set(fields.map(({ name }) => name));
62
+ const rest = ast.propertySignatures.filter(({ name }) => !names.has(name));
63
+ const { identifier: _identifierOfWholeSuccess, ...annotationsOfRest } = ast.annotations ?? {};
64
+ return {
65
+ fields,
66
+ rest: rest.length === 0 && ast.indexSignatures.length === 0 ? void 0 : Schema.make(new SchemaAST.Objects(rest, ast.indexSignatures, annotationsOfRest))
67
+ };
68
+ };
69
+ const liftedFrom = (lift, success) => lift.fields.flatMap(({ name, kind, many }) => {
70
+ const field = name !== void 0 && Predicate.hasProperty(success, name) ? success[name] : void 0;
71
+ const value = name === void 0 ? success : field;
72
+ const listed = isMediaArray(value) ? value : [];
73
+ const single = isMedia(value) ? [value] : [];
74
+ return (many ? listed : single).map((media) => ({
75
+ kind,
76
+ field: name,
77
+ value: media
78
+ }));
79
+ });
80
+ export { liftOf, liftedFrom };
@@ -2,8 +2,9 @@ import { Schema, SchemaAST } from "effect";
2
2
  /**
3
3
  * An image, a media field of a success: `{ data: Uint8Array, mimeType: string }`, `mimeType` such
4
4
  * as `image/png`. A top-level field of a struct success, one, optional, or a required array, or the
5
- * whole success, one or an array: an MCP tool lifts it into an image block of its own, and every other
6
- * surface sends it as JSON, the bytes in base64. `ActionMcp` refuses it anywhere else.
5
+ * whole success, one or an array: an MCP tool lifts it into an image block of its own, a toolkit tool
6
+ * into a file part of what its model reads, and every other surface sends it as JSON, the bytes in
7
+ * base64. `ActionMcp` refuses it anywhere else, and a toolkit sends it there in the JSON.
7
8
  *
8
9
  * **Gotchas**
9
10
  *
@@ -8,8 +8,9 @@ const Media = Schema.Struct({
8
8
  /**
9
9
  * An image, a media field of a success: `{ data: Uint8Array, mimeType: string }`, `mimeType` such
10
10
  * as `image/png`. A top-level field of a struct success, one, optional, or a required array, or the
11
- * whole success, one or an array: an MCP tool lifts it into an image block of its own, and every other
12
- * surface sends it as JSON, the bytes in base64. `ActionMcp` refuses it anywhere else.
11
+ * whole success, one or an array: an MCP tool lifts it into an image block of its own, a toolkit tool
12
+ * into a file part of what its model reads, and every other surface sends it as JSON, the bytes in
13
+ * base64. `ActionMcp` refuses it anywhere else, and a toolkit sends it there in the JSON.
13
14
  *
14
15
  * **Gotchas**
15
16
  *
@@ -1,6 +1,17 @@
1
- import { SchemaAST } from "effect";
1
+ import { Predicate, SchemaAST } from "effect";
2
2
  // src/contract/status.ts
3
- const httpApiStatusOf = SchemaAST.resolveAt("httpApiStatus");
3
+ const statusAnnotationsOf = (node) => {
4
+ for (const check of (node.checks ?? []).toReversed()) {
5
+ if (Predicate.hasProperty(check.annotations, "httpApiStatus")) return check.annotations;
6
+ const grouped = check._tag === "FilterGroup" ? statusAnnotationsOf(check) : void 0;
7
+ if (grouped !== void 0) return grouped;
8
+ }
9
+ return Predicate.hasProperty(node.annotations, "httpApiStatus") ? node.annotations : void 0;
10
+ };
11
+ const httpApiStatusOf = (ast) => {
12
+ const status = (statusAnnotationsOf(ast) ?? ast.context?.annotations)?.["httpApiStatus"];
13
+ return Predicate.isNumber(status) ? status : void 0;
14
+ };
4
15
  const transientStatuses = /* @__PURE__ */ new Set([
5
16
  408,
6
17
  429,
@@ -20,11 +20,11 @@ export declare const pageOf: <E extends Any>(event: E) => Schema.encodeKeys<Sche
20
20
  }>, {
21
21
  readonly nextPoll: "nextPollMs";
22
22
  }>;
23
- export declare const sentOf: <E extends Any>(event: E) => HttpApiSchema.StreamSse<HttpApiSchema.SseEventFromData<Schema.toCodecJson<Schema.Union<readonly [OccurrenceSchema<E>, Schema.TaggedStruct<"Gap", {
23
+ export declare const sentOf: <E extends Any>(event: E) => HttpApiSchema.StreamSse<HttpApiSchema.SseEventFromData<Schema.Union<readonly [OccurrenceSchema<E>, Schema.TaggedStruct<"Gap", {
24
24
  readonly cursor: Schema.NullOr<Schema.String>;
25
25
  }>, Schema.TaggedStruct<"Checked", {
26
26
  readonly cursor: Schema.NullOr<Schema.String>;
27
- }>, Schema.TaggedStruct<"Failed", {}>]>>>, Schema.Union<readonly [typeof Unauthenticated, typeof Forbidden]>, {
27
+ }>, Schema.TaggedStruct<"Failed", {}>]>>, Schema.Union<readonly [typeof Unauthenticated, typeof Forbidden]>, {
28
28
  readonly _tag: "Gap";
29
29
  readonly cursor: string | null;
30
30
  } | {
@@ -19,7 +19,7 @@ const pageOf = (event) => Schema.Struct({
19
19
  nextPoll: Schema.DurationFromMillis
20
20
  }).pipe(Schema.encodeKeys({ nextPoll: "nextPollMs" }));
21
21
  const sentOf = (event) => HttpApiSchema.StreamSse({
22
- data: Schema.toCodecJson(PushedOf(event)),
22
+ data: PushedOf(event),
23
23
  error: Refusal
24
24
  });
25
25
  const servedSent = HttpApiSchema.StreamSse({
@@ -10,15 +10,15 @@ import { pushed, refusalIn } from "../contract/push.mjs";
10
10
  import { promote } from "../authentication/provider.mjs";
11
11
  import { recordStepUp } from "../authentication/refusal.mjs";
12
12
  import { Active, EventsError, Failed, Heartbeat, Notifications, Occurred, Requests, Terminated, codes, extension, subscriptionIdKey } from "./events.mjs";
13
- import { isObjectSchema, routingFormsOf, toolJsonSchema } from "./protocol.mjs";
13
+ import { isObjectSchema, toolJsonSchema } from "./protocol.mjs";
14
14
  import { Cause, Context, Duration, Effect, Exit, Match, Option, Predicate, Result, Schema } from "effect";
15
15
  import { HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/http";
16
- import { McpSchema } from "effect/ai";
16
+ import { McpSchema, McpServer } from "effect/ai";
17
17
  // src/mcp/bridge.ts
18
18
  const isGroup = (u) => Predicate.isObjectKeyword(u) && "merge" in u && Predicate.isFunction(u.merge) && "requests" in u && u.requests instanceof Map;
19
19
  const groupOf = (adapter, key) => {
20
20
  const group = Predicate.hasProperty(adapter, key) ? adapter[key] : void 0;
21
- if (!isGroup(group)) throw new Error(`Effect's MCP ${adapter.protocolVersion} adapter holds no ${key} group: effect-actions supports MCP events on effect 4.0.x (install the effect version its peer range names)`);
21
+ if (!isGroup(group)) throw new Error(`Effect's MCP ${adapter.protocolVersion} adapter holds no ${key} group: effect-actions supports MCP events on effect 4.1.x (install the effect version its peer range names)`);
22
22
  return group;
23
23
  };
24
24
  const eventSchemasOf = (event) => {
@@ -47,7 +47,11 @@ const headerMismatch = (request) => Effect.andThen(HttpEffect.appendPreResponseH
47
47
  code: codes.headerMismatch,
48
48
  message: "Mcp-Name header does not match request parameters"
49
49
  })));
50
- const routedTo = (name) => Effect.flatMap(Effect.serviceOption(HttpServerRequest.HttpServerRequest), (request) => Option.isNone(request) || routingFormsOf(name).includes(request.value.headers["mcp-name"] ?? "") ? Effect.void : headerMismatch(request.value));
50
+ const routedTo = (name) => Effect.flatMap(Effect.serviceOption(HttpServerRequest.HttpServerRequest), (request) => {
51
+ if (Option.isNone(request)) return Effect.void;
52
+ const sent = request.value.headers["mcp-name"];
53
+ return sent !== void 0 && McpServer.decodeNameHeader(sent) === name ? Effect.void : headerMismatch(request.value);
54
+ });
51
55
  const servedOf = (feed, delivery) => {
52
56
  const { event } = feed;
53
57
  const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(event.input), inputParseOptions);
@@ -5,9 +5,10 @@ import { assertOnce } from "../contract/names.mjs";
5
5
  import { progressSink } from "../contract/progress.mjs";
6
6
  import { elementOf } from "../contract/stream.mjs";
7
7
  import { checked, checkedStream, sendingJson, watchInput } from "../contract/call.mjs";
8
+ import { liftOf } from "../contract/lift.mjs";
8
9
  import { split } from "../contract/listed.mjs";
9
10
  import { watching } from "../contract/watch.mjs";
10
- import { defaultPath, liftOf, unliftedFrom } from "./protocol.mjs";
11
+ import { defaultPath, unliftedFrom } from "./protocol.mjs";
11
12
  import { NoReply, NoStructuredContent, ProtocolError, StatusError, UndeclaredError, bodyOf, callError, failWith } from "./reply.mjs";
12
13
  import { request } from "./request.mjs";
13
14
  import { transportOf } from "./watch.mjs";
@@ -1,5 +1,4 @@
1
- import { unsuspended } from "../contract/ast.mjs";
2
- import { Media, isMarked, kindOf } from "../contract/media.mjs";
1
+ import { isMarked } from "../contract/media.mjs";
3
2
  import { JsonPointer, Predicate, Schema, SchemaAST } from "effect";
4
3
  import { Base64 } from "effect/encoding";
5
4
  import { McpProtocol, McpSchema } from "effect/ai";
@@ -34,72 +33,7 @@ const toolJsonSchema = (schema, strict) => {
34
33
  $defs: definitions
35
34
  };
36
35
  };
37
- const routingFormsOf = (name) => [name, `=?base64?${Base64.encode(name)}?=`];
38
36
  const fieldKey = "effect-actions/field";
39
- const isMedia = Schema.is(Media);
40
- const isMediaArray = Schema.is(Schema.Array(Media));
41
- const kindOfUnsuspended = (ast) => kindOf(unsuspended(ast));
42
- const wholeSuccessMediaOf = (suspended) => {
43
- const ast = unsuspended(suspended);
44
- const one = kindOf(ast);
45
- if (one !== void 0) return {
46
- kind: one,
47
- many: false
48
- };
49
- if (!SchemaAST.isArrays(ast) || ast.encoding !== void 0) return;
50
- const [kind, ...others] = new Set([...ast.elements, ...ast.rest].map(kindOfUnsuspended));
51
- return kind === void 0 || others.length > 0 ? void 0 : {
52
- kind,
53
- many: true
54
- };
55
- };
56
- const mediaFieldOf = (field) => {
57
- const optional = field.context?.isOptional === true;
58
- const ast = unsuspended(field);
59
- if (optional && SchemaAST.isUnion(ast) && ast.types.length === 2) {
60
- const [definedMember, ...otherDefinedMembers] = ast.types.filter((member) => !SchemaAST.isUndefined(member));
61
- const kind = definedMember === void 0 || otherDefinedMembers.length > 0 ? void 0 : kindOfUnsuspended(definedMember);
62
- return kind === void 0 ? void 0 : {
63
- kind,
64
- many: false
65
- };
66
- }
67
- const whole = wholeSuccessMediaOf(ast);
68
- return whole === void 0 || optional && whole.many ? void 0 : whole;
69
- };
70
- const liftOf = (success) => {
71
- const ast = unsuspended(success.ast);
72
- const whole = wholeSuccessMediaOf(ast);
73
- if (whole !== void 0) return {
74
- fields: [{
75
- name: void 0,
76
- ...whole
77
- }],
78
- rest: void 0
79
- };
80
- if (!SchemaAST.isObjects(ast) || ast.encoding !== void 0) return {
81
- fields: [],
82
- rest: success
83
- };
84
- const fields = ast.propertySignatures.flatMap(({ name, type }) => {
85
- const field = mediaFieldOf(type);
86
- return field === void 0 ? [] : [{
87
- name: String(name),
88
- ...field
89
- }];
90
- });
91
- if (fields.length === 0) return {
92
- fields,
93
- rest: success
94
- };
95
- const names = new Set(fields.map(({ name }) => name));
96
- const rest = ast.propertySignatures.filter(({ name }) => !names.has(name));
97
- const { identifier: _identifierOfWholeSuccess, ...annotationsOfRest } = ast.annotations ?? {};
98
- return {
99
- fields,
100
- rest: rest.length === 0 && ast.indexSignatures.length === 0 ? void 0 : Schema.make(new SchemaAST.Objects(rest, ast.indexSignatures, annotationsOfRest))
101
- };
102
- };
103
37
  const partsAndEncodedSideOf = (ast) => [
104
38
  ...SchemaAST.isDeclaration(ast) ? ast.typeParameters : [],
105
39
  ...SchemaAST.isArrays(ast) ? [...ast.elements, ...ast.rest] : [],
@@ -124,17 +58,6 @@ const isMisplaced = (action, { rest }) => [
124
58
  ...action.error,
125
59
  ...rest === void 0 ? [] : [rest]
126
60
  ].some(({ ast }) => holdsMediaAnywhere(ast));
127
- const liftedFrom = (lift, success) => lift.fields.flatMap(({ name, kind, many }) => {
128
- const field = name !== void 0 && Predicate.hasProperty(success, name) ? success[name] : void 0;
129
- const value = name === void 0 ? success : field;
130
- const listed = isMediaArray(value) ? value : [];
131
- const single = isMedia(value) ? [value] : [];
132
- return (many ? listed : single).map((media) => ({
133
- kind,
134
- field: name,
135
- value: media
136
- }));
137
- });
138
61
  const mediaOf = ({ name, kind, many }, result) => {
139
62
  const values = result.content.flatMap((block) => block.type === kind && block._meta?.["effect-actions/field"] === name ? [{
140
63
  data: Base64.encode(block.data),
@@ -153,4 +76,4 @@ const unliftedFrom = (lift, result) => {
153
76
  return field.name === void 0 || value === void 0 ? [] : [[field.name, value]];
154
77
  })]);
155
78
  };
156
- export { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, liftOf, liftedFrom, protocols, routingFormsOf, toolJsonSchema, unliftedFrom };
79
+ export { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, protocols, toolJsonSchema, unliftedFrom };
@@ -1,6 +1,7 @@
1
1
  import { sha256Hex } from "../contract/digest.mjs";
2
2
  import { Effect } from "effect";
3
3
  import { Base64, Hex } from "effect/encoding";
4
+ import { Mac } from "effect/crypto";
4
5
  // src/webhook/signing.ts
5
6
  const encoder = new TextEncoder();
6
7
  const hmac = (key, content) => Effect.promise(async () => {
@@ -17,9 +18,5 @@ const hmac = (key, content) => Effect.promise(async () => {
17
18
  const signature = (keys, id, timestamp, body) => Effect.map(Effect.forEach(keys, (key) => hmac(key, `${id}.${timestamp}.${body}`)), (signed) => signed.map((bytes) => `v1,${Base64.encode(bytes)}`).join(" "));
18
19
  const subscriptionId = (key) => Effect.map(sha256Hex(key), (hex) => `sub_${hex.slice(0, 32)}`);
19
20
  const randomToken = Effect.sync(() => Hex.encode(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
20
- const constantTimeEqual = (a, b) => {
21
- const left = encoder.encode(a);
22
- const right = encoder.encode(b);
23
- return left.length === right.length && left.reduce((differs, byte, index) => differs | byte ^ (right[index] ?? 0), 0) === 0;
24
- };
21
+ const constantTimeEqual = (a, b) => Mac.timingSafeEqual(encoder.encode(a), encoder.encode(b));
25
22
  export { constantTimeEqual, randomToken, signature, subscriptionId };
@@ -1,7 +1,7 @@
1
1
  import { reported } from "../contract/reported.mjs";
2
2
  import { CallbackUrl, WebhookSecret } from "../contract/callback.mjs";
3
3
  import { DeliveryStatus } from "../contract/subscribe.mjs";
4
- import { Duration, Effect, Option, Queue, Schema, Semaphore } from "effect";
4
+ import { Cause, Duration, Effect, Option, Queue, Schema, Semaphore } from "effect";
5
5
  import { KeyValueStore } from "effect/persistence";
6
6
  // src/webhook/stored.ts
7
7
  const Stored = Schema.Struct({
@@ -14,34 +14,44 @@ const Stored = Schema.Struct({
14
14
  watermark: Schema.NullOr(Schema.String),
15
15
  status: DeliveryStatus
16
16
  });
17
- const prefix = "effect-actions/webhook";
18
- const Index = Schema.Array(Schema.String);
17
+ const prefix = "effect-actions/webhook/";
19
18
  const flushTimeout = Duration.seconds(5);
19
+ var UnfinishedWrites = class UnfinishedWrites extends Schema.TaggedError()("UnfinishedWrites", {
20
+ ids: Schema.Array(Schema.String),
21
+ message: Schema.String
22
+ }) {
23
+ static of(ids) {
24
+ return new UnfinishedWrites({
25
+ ids,
26
+ message: `Webhook.layer closed with subscriptions ${ids.join(", ")} unwritten after ${Duration.format(flushTimeout)}: the store keeps each one's last write`
27
+ });
28
+ }
29
+ };
20
30
  const makeWriteBehindStorage = (store) => Effect.gen(function* () {
21
- const records = KeyValueStore.toSchemaStore(KeyValueStore.prefix(store, `${prefix}/`), Stored);
22
- const index = KeyValueStore.toSchemaStore(store, Index);
23
- let indexed = new Set(yield* Effect.orDie(Effect.map(index.get(prefix), Option.getOrElse(() => []))));
31
+ const records = KeyValueStore.toSchemaStore(KeyValueStore.prefix(store, prefix), Stored);
32
+ const kept = new Set(yield* Effect.orDie(records.keys));
24
33
  const pending = /* @__PURE__ */ new Map();
25
34
  const marked = yield* Queue.sliding(1);
26
35
  const writing = Semaphore.makeUnsafe(1);
27
- const listed = (next) => Effect.andThen(index.set(prefix, [...next]), Effect.sync(() => {
28
- indexed = next;
36
+ const written = (id, record) => Effect.andThen(record === void 0 ? records.remove(id) : records.set(id, record), Effect.sync(() => {
37
+ if (record === void 0) kept.delete(id);
38
+ else kept.add(id);
29
39
  }));
30
- const removedThenUnlisted = (id) => Effect.andThen(records.remove(id), Effect.suspend(() => indexed.has(id) ? listed(new Set([...indexed].filter((each) => each !== id))) : Effect.void));
31
- const listedThenKept = (id, record) => Effect.andThen(Effect.suspend(() => indexed.has(id) ? Effect.void : listed(/* @__PURE__ */ new Set([...indexed, id]))), records.set(id, record));
32
- const written = (id, record) => record === void 0 ? removedThenUnlisted(id) : listedThenKept(id, record);
33
40
  const clearedUnlessRemarked = (id, record) => Effect.sync(() => {
34
41
  if (pending.get(id) === record) pending.delete(id);
35
42
  });
36
43
  const flushed = writing.withPermits(1)(Effect.suspend(() => Effect.forEach([...pending], ([id, record]) => written(id, record).pipe(Effect.andThen(clearedUnlessRemarked(id, record)), Effect.catchCause(reported)), { discard: true })));
37
44
  yield* Effect.forkScoped(Effect.forever(Effect.andThen(Queue.take(marked), flushed)));
38
- yield* Effect.addFinalizer(() => flushed.pipe(Effect.timeout(flushTimeout), Effect.ignore));
45
+ yield* Effect.addFinalizer(() => Effect.timeoutOrElse(flushed, {
46
+ duration: flushTimeout,
47
+ orElse: () => reported(Cause.fail(UnfinishedWrites.of([...pending.keys()])))
48
+ }));
39
49
  return {
40
50
  mark: (id, record) => {
41
51
  pending.set(id, record);
42
52
  Queue.offerUnsafe(marked, void 0);
43
53
  },
44
- ids: () => [.../* @__PURE__ */ new Set([...indexed, ...pending.keys()])],
54
+ ids: () => [.../* @__PURE__ */ new Set([...kept, ...pending.keys()])],
45
55
  get: (id) => pending.has(id) ? Effect.succeed(Option.fromUndefinedOr(pending.get(id))) : records.get(id)
46
56
  };
47
57
  });
@@ -20,7 +20,7 @@ What you see when something is wrong, and the fix. Search for a fragment of the
20
20
 
21
21
  ## Client methods
22
22
 
23
- - `HttpClientError` whose `reason._tag` is `DecodeError`, printed `Decode error (<status> …)`, for a status such as 429: no schema declares that status; declare the error on the binding when middleware answers with it, on the action when its handler does. For a 500, the cause is in the server's logs.
23
+ - `HttpClientError` whose `reason._tag` is `DecodeError`, printed `Decode: undeclared status code (<status> …)`, for a status such as 429: no schema declares that status; declare the error on the binding when middleware answers with it, on the action when its handler does. For a 500, the cause is in the server's logs.
24
24
  - `HttpClientError` whose `reason._tag` is `InvalidUrlError` outside a browser: relative routes have no page to resolve against; set `baseUrl`.
25
25
  - Type error listing `HttpClient` as an unsatisfied requirement: provide one, such as `FetchHttpClient.layer`, or use `ActionHttp.fetchClient`.
26
26
  - `Expected 1 arguments` at a client method: `{}` is not a valid input for the action, so pass its input; where the argument may be omitted, leave it out, as `undefined` is a type error.
@@ -3,7 +3,8 @@
3
3
  What you see when something is wrong, and the fix. Search for a fragment of the message. The tasks are in [ActionMcp.md](ActionMcp.md).
4
4
 
5
5
  - `Type 'X' is not assignable to type 'never'` where the server is launched, or `Request<"Requires", X>` in an MCP endpoint's type: a handler or an authorizer yields a request service no middleware around the endpoint provides. Provide it with router middleware. `X` the identity, on an endpoint serving public tools: a public handler reads it, which no public tool gets, signed in or not. Make that action protected.
6
- - `Type 'CurrentUser' is not assignable to type 'never'` where the server is launched, with `CurrentUser` among an MCP endpoint's startup requirements, not its `Request<"Requires", ...>`: a native feature reads a request service, which features never receive. Serve that content as an action.
6
+ - `Type 'CurrentUser' is not assignable to type 'never'` where the server is launched, with `CurrentUser` among an MCP endpoint's startup requirements, not its `Request<"Requires", ...>`: a native feature's `Layer.unwrap` reads a request service at startup, when there is no caller. Content that depends on the caller is an action.
7
+ - `Service not found: effect/ai/McpServer` as a layer builds, or `McpServer` among a layer's requirements: a native feature is merged beside the endpoint. Pass it as `features`.
7
8
  - `Type 'CurrentUser' is not assignable to type 'never'` at a stdio program's `runMain`: it serves a protected tool, whose caller the host supplies. Provide the identity around `runStdio`.
8
9
  - A client that opens with `initialize`, such as Codex, gets 400 with JSON-RPC error `-32020`, `MCP-Protocol-Version header is required`, or 401 signed out where the endpoint serves a protected tool, and a `DELETE` gets 405: the endpoint is `requestScoped`, which speaks MCP 2026-07-28 alone and keeps no session. Connect that client to an endpoint without it, on a host that keeps a process running.
9
10
  - `subscriptions/listen` answered with JSON-RPC error `-32601`, Method not found: an endpoint without `features` has no 2026-07-28 subscriptions unless `allowSubscriptions` is `true`, and a `requestScoped` one has none. Pass `true` where a handler changes the server through `McpServer.McpServer`.
package/docs/ActionMcp.md CHANGED
@@ -27,7 +27,7 @@ export const routes = Layer.mergeAll(
27
27
  - Claude Code 2.1 and Codex CLI 0.162 connect: `claude mcp add --transport http <name> <url>/mcp --header "Authorization: Bearer <token>"`, `codex mcp add <name> --url <url>/mcp --bearer-token-env-var <VAR>`; [mcp-tools](../examples/mcp-tools/README.md#connect-a-client) has stdio and Claude Desktop.
28
28
  - Where an endpoint without `authentication` listens, and its body limit: [mcp-tools/src/server.ts](../examples/mcp-tools/src/server.ts).
29
29
  - **On a serverless host**, such as Cloudflare Workers, pass `requestScoped: true`: [notes-service/src/worker.ts](../examples/notes-service/src/worker.ts). For an endpoint in a Cloudflare Durable Object: the `@gjermundgaraba/effect-actions-cloudflare` package's docs.
30
- - The endpoint takes no layer middleware. A limit that must hold for tools goes in the handlers: [kitchen-sink/src/issues/write-limit.ts](../examples/kitchen-sink/src/issues/write-limit.ts).
30
+ - `McpServer.middleware` and `McpServer.visibility` provided around the endpoint run for its tools and its native features alike. A limit that must hold on every surface goes in the handlers: [kitchen-sink/src/issues/write-limit.ts](../examples/kitchen-sink/src/issues/write-limit.ts).
31
31
 
32
32
  ## Serve tools over stdio
33
33
 
@@ -77,7 +77,7 @@ Give the success an `Action.Image` field and return its bytes and MIME type from
77
77
 
78
78
  Name the protected actions' authentication descriptor as `authentication` and provide its provider to the routes: [notes-service/src/routes.ts](../examples/notes-service/src/routes.ts). Write the [descriptor](Authentication.md#declare-how-callers-sign-in) and its [provider](Authentication.md#verify-credentials) once for every surface, and [publish discovery](Authentication.md#publish-oauth-discovery) so an MCP client finds where to sign in. What a signed-in caller may do is each implementation's [`authorize`](Action.md#authorize-calls), which runs on every call of a protected tool.
79
79
 
80
- - **One endpoint or two.** What a mixed endpoint, serving public and protected tools, shows and runs signed out is on `ActionMcp.LayerHttpOptions`'s `authentication`.
80
+ - **One endpoint or two.** What a mixed endpoint, serving public and protected tools, shows and runs signed out, and how to hide its protected tools then, is on `ActionMcp.LayerHttpOptions`'s `authentication`.
81
81
  - Test as a signed-in caller ([Testing.md](Testing.md#test-as-a-signed-in-caller)): [notes-service/test/routes.test.ts](../examples/notes-service/test/routes.test.ts).
82
82
 
83
83
  ## Serve events
@@ -45,6 +45,7 @@ export const actingFor = (member: Member) =>
45
45
  [assistant/src/agent.ts](../examples/assistant/src/agent.ts) runs the turns and provides `layer` with its startup services, with a scripted model in [assistant/src/scripted.ts](../examples/assistant/src/scripted.ts). What a call returns, a refusal and arguments that do not decode included, is on `ActionToolkit.make`; the options' rules are on `ActionToolkit.Options`.
46
46
 
47
47
  - **Let the model read its tools' results** by asking again: [kitchen-sink/src/assistant/handlers.ts](../examples/kitchen-sink/src/assistant/handlers.ts).
48
+ - **Show the model an image** by giving the success an `Action.Image` field, as `get_camera_snapshot` does in [mcp-tools/src/printers/Printers.ts](../examples/mcp-tools/src/printers/Printers.ts): the model reads the image as a file and the other fields as JSON. Where an image is lifted is on `Action.Image`; what a provider that takes only text reads is on `ActionToolkit.make`.
48
49
  - Where a model must not get every action, list the tools ([Action.md](Action.md#define-a-contract)): [kitchen-sink/src/issues/assistant.ts](../examples/kitchen-sink/src/issues/assistant.ts).
49
50
  - A turn's tool calls, the approved calls of an answering turn included, run concurrently unless `generateText` is given a `concurrency`: [assistant/src/tasks/store.ts](../examples/assistant/src/tasks/store.ts) locks each change.
50
51
  - **A model loop behind a route.** Yield `toolkit` and the model in the implementation's builder, and provide `layer` to the route's layer, `ActionHttp.layer(Http, ask).pipe(Layer.provide(layer))`, so the tools share the routes' build ([Action.md](Action.md#share-one-build-across-servers)): [kitchen-sink/src/assistant/handlers.ts](../examples/kitchen-sink/src/assistant/handlers.ts), keeping each caller's `Chat` in [conversations.ts](../examples/kitchen-sink/src/assistant/conversations.ts), with a scripted model in [demo-model.ts](../examples/kitchen-sink/src/assistant/demo-model.ts) that the entrypoint provides through [kitchen-sink/src/memory.ts](../examples/kitchen-sink/src/memory.ts), tested over HTTP in [kitchen-sink/test/assistant/assistant.test.ts](../examples/kitchen-sink/test/assistant/assistant.test.ts). Name the files as it does, the route's contract `Assistant.ts` and the loop `handlers.ts`, from the first one written.
package/docs/README.md CHANGED
@@ -28,7 +28,7 @@ Where things are, in a project that installs the package: these pages in `node_m
28
28
  | [ActionMcp.md](ActionMcp.md) | serve MCP tools over HTTP or stdio, describe them to a model, return images, protect them, serve events, allow browser clients, add prompts and resources, send notifications |
29
29
  | [ActionRpc.md](ActionRpc.md) | bind actions to Effect rpcs, serve them on a protocol, call them, add native rpcs, send request context with a call |
30
30
  | [ActionRpc-events.md](ActionRpc-events.md) | serve and watch events over rpcs, follow what a request names, such as a room |
31
- | [ActionToolkit.md](ActionToolkit.md) | give a model actions as a native Effect AI `Toolkit`, name the caller, ask for approval |
31
+ | [ActionToolkit.md](ActionToolkit.md) | give a model actions as a native Effect AI `Toolkit`, show it images, name the caller, ask for approval |
32
32
  | [ActionCli.md](ActionCli.md) | run actions as local commands, or call a server from commands; watch events; shape flags, input and output; name the caller; add a command of your own |
33
33
  | [Webhook.md](Webhook.md) | deliver events to a subscriber's callback by webhook, signed, and watch by webhook |
34
34
  | [Authentication.md](Authentication.md) | declare how callers sign in, verify credentials, publish OAuth discovery, step up for a scope |
@@ -2,7 +2,7 @@
2
2
 
3
3
  What you see when something is wrong, and the fix. Search for a fragment of the message. A missing service's error can start `… with 'exactOptionalPropertyTypes: true'. Consider adding 'undefined'`: search a line beneath it, `is missing the following properties from type 'Scope'`, instead. The tasks are in [Testing.md](Testing.md).
4
4
 
5
- - A route answers an empty 500, which a client method reports as `HttpClientError: Decode error (500 …)`: a defect, or a result that does not encode. `Testing.layer(routes)` logs its cause on the process console, under `it.effect` too: read the test's output, or collect it with a `Logger` provided around the layer.
5
+ - A route answers an empty 500, which a client method reports as `HttpClientError: Decode: undeclared status code (500 …)`: a defect, or a result that does not encode. `Testing.layer(routes)` logs its cause on the process console, under `it.effect` too: read the test's output, or collect it with a `Logger` provided around the layer.
6
6
  - `Type 'Provider<CurrentUser, "notes-service.Login">' is missing the following properties from type 'Scope'` at `it.effect`, or `… is not assignable to type 'never'` at `Effect.runPromise`: the routes serve a protected action without a provider of its descriptor. Provide the real one or a test verifier to the routes; a caller provided around `Testing.layer` does not satisfy them.
7
7
  - `Type 'CurrentUser' is missing the following properties from type 'Scope'` at `it.effect`, or `… is not assignable to type 'never'` at `Effect.runPromise`: the test still owes the identity. An `Action.client` call of a protected action takes its caller per call: provide it around the call. Or a public action's handler reads the identity, which no route provides to it: make the action protected. Or, where the caller is provided already, a builder yields it: move that `yield*` into the handler ([Action-failures.md](Action-failures.md#where-an-implementation-is-served)).
8
8
  - `Type '<Service>' is missing the following properties from type 'Scope'` at every `it.effect`, for a service that is no identity, such as a store, a limiter or a `LanguageModel`: a builder now yields it, and the routes require it. Provide its layer to `Testing.layer(routes)`, as the entrypoint provides it to the server.
@@ -8,5 +8,5 @@ What you see when something is wrong, and the fix. Search for a fragment of the
8
8
  - A page that loads Effect from an import map still bundles a second copy of Effect or of some of its modules, or fails to resolve `effect/Schema` in the browser when its bundler externalizes subpaths, as esbuild's `--external:effect` does: a module of the page imports an Effect specifier the map does not serve. Serve the specifiers [Bundle for a browser](setup.md#bundle-for-a-browser) lists, and import Effect through them in the page's own modules too.
9
9
  - A page loading Effect from an import map fails with `Failed to resolve module specifier "effect/Cause"` in Chromium: the map points at Effect's published files and lacks a specifier Effect imports itself. Map `effect/Cause`, `effect/Effect`, `effect/Exit` and `effect/Function` to the same files, or serve Effect from a build that resolves its own imports.
10
10
  - A page fails at load with `does not provide an export named …`: it serves only the names it uses of an Effect specifier, from a vendored module or a trimmed bundle, and the package imports another. Serve each specifier whole.
11
- - Type errors inside `effect/*` modules after install, an unmet peer warning for `effect`, such as `found 4.1.0`, or a start failing with `Cannot find module '…/effect/dist/…'` under an `@effect/*` package: more than one Effect release is installed, or one outside the peer range. Install the `effect` range [Install](setup.md#install) names, with every `@effect/*` package at the version `effect` resolved to, such as `@effect/platform-node@4.0.5` beside `effect@4.0.5`.
11
+ - Type errors inside `effect/*` modules after install, an unmet peer warning for `effect`, such as `found 4.2.0`, or a start failing with `Cannot find module '…/effect/dist/…'` under an `@effect/*` package: more than one Effect release is installed, or one outside the peer range. Install the `effect` range [Install](setup.md#install) names, with every `@effect/*` package at the version `effect` resolved to, such as `@effect/platform-node@4.1.1` beside `effect@4.1.1`.
12
12
  - `Cannot find module 'effect/unstable/http'` (or `…/httpapi`, `…/cli`, `…/ai`): these modules are now `effect/http`, `effect/http-api`, `effect/cli` and `effect/ai`.
package/docs/setup.md CHANGED
@@ -7,20 +7,20 @@ A message the library throws says its fix; for a compiler diagnostic or Effect's
7
7
  ## Install
8
8
 
9
9
  ```sh
10
- pnpm add @gjermundgaraba/effect-actions effect@~4.0.5
10
+ pnpm add @gjermundgaraba/effect-actions effect@~4.1.1
11
11
  ```
12
12
 
13
13
  | Need | Add |
14
14
  | --- | --- |
15
- | Node HTTP server, stdio host or CLI | `@effect/platform-node@~4.0.5` |
16
- | Tests | `vitest@^5` and `@effect/vitest@~4.0.5`, as dev dependencies |
15
+ | Node HTTP server, stdio host or CLI | `@effect/platform-node@~4.1.1` |
16
+ | Tests | `vitest@^5` and `@effect/vitest@~4.1.1`, as dev dependencies |
17
17
  | Type checking | `typescript@^7.0.2`, as a dev dependency |
18
18
  | Node's types, for `node:` imports | `@types/node`, as a dev dependency |
19
19
  | Running a TypeScript entrypoint | `tsx`, as a dev dependency: `node --import tsx <entrypoint>.ts` |
20
20
 
21
- The `effect` peer admits the 4.0.x patches from the oldest whose APIs the package uses, and no minor release: a minor release may change the unstable Effect modules the surfaces build on.
21
+ The `effect` peer admits the 4.1.x patches from the oldest whose APIs and behavior the package relies on, and no minor release: a minor release may change the unstable Effect modules the surfaces build on.
22
22
 
23
- Keep the tilde in `package.json`: `^4.0.5`, which npm writes for `effect@4.0.5`, admits a minor release outside the peer range. `npm install effect@~4.0.5` keeps it.
23
+ Keep the tilde in `package.json`: `^4.1.1`, which npm writes for `effect@4.1.1`, admits a minor release outside the peer range. `npm install effect@~4.1.1` keeps it.
24
24
 
25
25
  Node `>=26.12.0`: the package's `engines`, the Node the library is developed and tested on. TypeScript 7 or newer. ESM only. The repository checks the examples with a stricter `tsconfig.json`; this is the minimum a project needs. The package's modules resolve only through its `exports`, which `"module": "nodenext"` reads, as a bundler project's `"moduleResolution": "bundler"` does. `"strict": true` is required, by Effect:
26
26
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/effect-actions",
3
- "version": "0.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "Define Effect action contracts once and project them onto HTTP, MCP, Effect RPC, native Toolkits, and CLIs.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -52,14 +52,13 @@
52
52
  },
53
53
  "devDependencies": {
54
54
  "@clanker-stuff/oxlint-config": "0.1.0",
55
- "@effect/platform-node": "4.0.6",
55
+ "@effect/platform-node": "4.1.1",
56
56
  "@effect/tsgo": "0.57.0",
57
- "@effect/vitest": "4.0.6",
57
+ "@effect/vitest": "4.1.1",
58
58
  "@modelcontextprotocol/client": "2.3.1",
59
59
  "@types/node": "26.6.5",
60
- "effect": "4.0.6",
60
+ "effect": "4.1.1",
61
61
  "oxfmt": "0.74.0",
62
- "oxlint": "1.89.0",
63
62
  "tsx": "4.23.15",
64
63
  "typescript": "7.0.2",
65
64
  "ultracite": "8.0.2",
@@ -68,7 +67,7 @@
68
67
  "vitest": "5.0.5"
69
68
  },
70
69
  "peerDependencies": {
71
- "effect": "~4.0.5"
70
+ "effect": "~4.1.1"
72
71
  },
73
72
  "devEngines": {
74
73
  "packageManager": {