@gjermundgaraba/effect-actions 0.39.1 → 0.41.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.1.4
79
+ pnpm add @gjermundgaraba/effect-actions effect@~4.2.0
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.1.4` 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.2.0` 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
 
@@ -9,13 +9,15 @@ import { Params, RequestOptions, request } from "./mcp/request.mjs";
9
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
+ type NativeStdioOptions = Parameters<typeof McpServer.layerStdio>[0];
13
+ type NativeHttpOptions = Parameters<typeof McpServer.layerHttp>[0];
12
14
  /**
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
15
+ * An MCP server, over HTTP or stdio: every native option `McpServer.layerStdio` and
16
+ * `McpServer.layerHttp` both take but `protocols` and `registrations`, the server information,
17
+ * `instructions`, `extensions` and `cacheHints` among them, the actions `A` that are its tools and the event types `A` it serves, and the
16
18
  * native features it serves beside them.
17
19
  */
18
- export interface Options<E = never, R = never, A extends Any$1 | Any$2 = Any$1 | Any$2> extends Omit<Parameters<typeof McpServer.layerStdio>[0], "protocols" | "registrations"> {
20
+ export interface Options<E = never, R = never, A extends Any$1 | Any$2 = Any$1 | Any$2> extends Omit<Pick<NativeStdioOptions, keyof NativeStdioOptions & keyof NativeHttpOptions>, "protocols" | "registrations"> {
19
21
  /**
20
22
  * The actions that are tools and the event types it serves, among the implementations':
21
23
  * `[GetUser, RenameUser, UserRenamed]`, exactly those. Each keeps its implementation's
@@ -44,10 +46,10 @@ export interface Options<E = never, R = never, A extends Any$1 | Any$2 = Any$1 |
44
46
  }
45
47
  /**
46
48
  * One Streamable HTTP MCP endpoint: `Options`, `authentication`, `requestScoped`, and every native
47
- * `McpServer.layerHttp` option, `allowedOrigins` among them, except `protocols`, `registrations`
48
- * and `allowSessionTermination`, which are fixed.
49
+ * `McpServer.layerHttp` option, `allowedOrigins` and `maxSessions` among them, except `protocols`,
50
+ * `registrations` and `allowSessionTermination`, which are fixed.
49
51
  */
50
- export interface LayerHttpOptions<E = never, R = never, A extends Any$1 | Any$2 = Any$1 | Any$2> extends Options<E, R, A>, Omit<Parameters<typeof McpServer.layerHttp>[0], "protocols" | "path" | "allowSessionTermination" | "registrations"> {
52
+ export interface LayerHttpOptions<E = never, R = never, A extends Any$1 | Any$2 = Any$1 | Any$2> extends Options<E, R, A>, Omit<NativeHttpOptions, "protocols" | "path" | "allowSessionTermination" | "registrations"> {
51
53
  /** The endpoint's route; defaults to `/mcp`. */
52
54
  readonly path?: HttpRouter.PathInput;
53
55
  /**
@@ -104,7 +106,9 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
104
106
  * Serve MCP tools over one Streamable HTTP endpoint, speaking MCP 2026-07-28, 2025-11-25 or
105
107
  * 2025-06-18, as the client negotiates. A 2026-07-28 request stands alone; a client of a 2025
106
108
  * revision opens a session with `initialize`, which holds what it sent there and no identity,
107
- * and lasts until that client ends it with a DELETE, answered 204, or the process stops. Protected
109
+ * and lasts until that client ends it with a DELETE, answered 204, or the process stops, or until
110
+ * it is the least recently used idle one beyond the native `maxSessions`, whose id is then
111
+ * answered 404. Protected
108
112
  * tools need `authentication`; for a serverless host, see `requestScoped`. In a tool call, what
109
113
  * middleware provides per request wins over what the endpoint was built with. The event
110
114
  * types among `implementations`, or those `actions` lists, are served as SEP-3415 events,
@@ -118,12 +122,13 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
118
122
  *
119
123
  * - A success is `isError: false` with `structuredContent` its JSON and the same JSON as one text block, both `null` for an action without `success`; an `Action.Image` field is left out of `structuredContent` and its text, its block following them, and a success of images alone has no `structuredContent`.
120
124
  * - A success whose schema encodes only to a string, such as `Schema.String`, a string literal or `Schema.DateTimeUtc`, is its raw text as one text block on every revision, with no `structuredContent` and no `outputSchema`, since Claude Code shows a model serialized `structuredContent` in place of every text block: return file contents or command output as such a string, never as a field of an object, which reaches a model JSON-escaped.
125
+ * - A union success of `Action.Image`, or an array of it, and members that encode only to a string, such as `Schema.Union([Schema.String, Action.Image])`, answers a string as its raw text block alone and media as its image blocks alone, with no `structuredContent` and no `outputSchema`; a union of media and a member that encodes to anything else is refused as the endpoint is made.
121
126
  * - A union holding a string, such as `Schema.NullOr(Schema.String)` or an optional string, is sent as any other success, so a 2026-07-28 client gets the string as `structuredContent` and JSON-quoted text, which reaches a Claude Code model escaped: return `""` for nothing, not `null`.
122
- * - A declared error is an `isError: true` tool result in a 200 whose one text block is its `message`, or the error itself when it is a string, or its JSON when it has no `message` or an empty one, with its JSON in `_meta["io.github.gjermundgaraba.effect-actions/error"]`, from which `client` decodes it, and no `structuredContent`: write each `message` for the model, since its other fields reach a model only through it; a refusal is answered as `Action.Unauthenticated` and `Action.Forbidden` say.
127
+ * - A declared error is an `isError: true` tool result in a 200 whose one text block is its `message`, or the error itself when it is a string, or its JSON when it has no `message` or an empty one, with its JSON in `_meta["io.github.gjermundgaraba.effect-actions/error"]`, from which `client` decodes it, Effect's `McpSchema.ToolErrorInfo` `{ kind: "failure" }` in `_meta["website.effect/toolError"]`, with `tag` its `_tag` where it has a non-empty one, and no `structuredContent`: write each `message` for the model, since its other fields reach a model only through it; a refusal is answered as `Action.Unauthenticated` and `Action.Forbidden` say.
123
128
  * - An action answering a stream, `Action.Stream`, answers its elements collected into one array once the stream ends, a success of that array.
124
129
  * - An action declaring `progress` sends each value as `notifications/progress` on the `progressToken` its call's `_meta` carries, before the result: `progress` counts from 1, `message` is the value's JSON and `_meta["io.github.gjermundgaraba.effect-actions/progress"]` the value; a call without a token gets none.
125
- * - Arguments that do not decode never reach the handler: an `isError: true` result in a 200, text `Invalid parameters for tool '<name>': …`, or for a 2025-06-18 client a JSON-RPC error.
126
- * - A defect, an undeclared failure, or a success or an error that does not encode is `isError: true`, text `Tool execution failed due to an internal server error.`: the cause goes to the log and to the call's `ErrorReporter`s, never to the client.
130
+ * - Arguments that do not decode never reach the handler: an `isError: true` result in a 200, text `Invalid parameters for tool '<name>': …` with `{ kind: "invalidInput" }` in `_meta["website.effect/toolError"]`, or for a 2025-06-18 client a JSON-RPC error.
131
+ * - A defect, an undeclared failure, or a success or an error that does not encode is `isError: true`, text `Tool execution failed due to an internal server error.`, with `{ kind: "internal" }` in `_meta["website.effect/toolError"]`: the cause goes to the log and to the call's `ErrorReporter`s, never to the client.
127
132
  * - An unknown tool is a JSON-RPC error `-32602` in a 200; a body that is not JSON a JSON-RPC error `-32700` in a 200; a `Content-Type` missing or not JSON a JSON-RPC error `-32600` in a 415; another HTTP method an empty 405 with `Allow: POST, DELETE`, `Allow: POST` where `requestScoped`, or the 401 of an endpoint with authentication when signed out.
128
133
  * - A 2025-11-25 or 2025-06-18 client gets `structuredContent` only for a success that is an object: a number, an array or `null` arrives as its JSON text block alone, and a string a union success returns as its text unquoted.
129
134
  * - A client asking for an earlier revision, such as 2025-03-26, is offered 2025-11-25, so a client speaking only that earlier one cannot connect.
@@ -137,11 +142,17 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
137
142
  * - 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.
138
143
  */
139
144
  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 | 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>>;
145
+ /**
146
+ * `runStdio`'s options: `Options` and every native `McpServer.layerStdio` option, `onStdinEnd`
147
+ * among them, except `protocols` and `registrations`, which are fixed.
148
+ */
149
+ export interface RunStdioOptions<E = never, R = never, A extends Any$1 | Any$2 = Any$1 | Any$2> extends Options<E, R, A>, Omit<NativeStdioOptions, "protocols" | "registrations"> {}
140
150
  /**
141
151
  * Serve MCP tools through newline-delimited JSON-RPC on standard I/O, speaking MCP
142
152
  * 2026-07-28, 2025-11-25 or 2025-06-18, as the host negotiates: the whole
143
153
  * program of an MCP subprocess, which succeeds once the host closes its side and every call
144
- * in flight has been answered. A signal interrupts it. Its own Effect logs and `Console` output
154
+ * in flight has been answered, or, with `onStdinEnd: "interrupt"`, once the host closes its
155
+ * side, interrupting the calls in flight unanswered. A signal interrupts it. Its own Effect logs and `Console` output
145
156
  * go to stderr, since stdout carries the protocol. The host supplies the `Stdio` service, and
146
157
  * provides the identity around `runStdio`; arguments are tool input only and never establish
147
158
  * request identity or authority, and each implementation's `authorize` runs for its protected
@@ -150,8 +161,8 @@ export declare function layerHttp<const Apps extends Served, const O extends Sel
150
161
  *
151
162
  * **Gotchas**
152
163
  *
153
- * - A line that is not JSON goes unanswered, with no `-32700` as over HTTP, and the lines after it are still answered.
164
+ * - A line that is not JSON is answered `-32700` with `id: null`, as over HTTP, and a line of JSON that is no JSON-RPC message, such as `5` or `{}`, `-32600`; the lines after either are still answered.
154
165
  * - The layers provided around it log to stdout, among the protocol's lines: apply `ActionCli.logToStderr` to the program, last, as its JSDoc says.
155
166
  */
156
- 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>>;
167
+ 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: RunStdioOptions<E, R, ActionOf<Member<Apps>> | EventOf<Member<Apps>>> & O & NoInfer<Known<O, RunStdioOptions<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>>;
157
168
  export { type Client, type ClientOptions, McpCallError, type Params, type RequestOptions, client, request };
@@ -17,7 +17,7 @@ import { defaultPath, errorKey, fieldKey, httpProtocol, isMisplaced, isObjectSch
17
17
  import { client } from "./mcp/client.mjs";
18
18
  import { McpCallError } from "./mcp/reply.mjs";
19
19
  import { request } from "./mcp/request.mjs";
20
- import { Cause, Context, Effect, ErrorReporter, Exit, Fiber, Layer, Option, Predicate, Schema, Stdio, Stream } from "effect";
20
+ import { Cause, Context, Effect, ErrorReporter, Exit, Fiber, Layer, Predicate, Schema } from "effect";
21
21
  import { HttpRouter, HttpServerRequest } from "effect/http";
22
22
  import { AiError, McpSchema, McpServer } from "effect/ai";
23
23
  // src/mcp/ActionMcp.ts
@@ -25,15 +25,15 @@ const assertToolsServable = (lifted) => {
25
25
  const inputs = lifted.map(([action]) => action).flatMap(({ input, name }) => isObjectSchema(toolJsonSchema(Schema.toCodecJson(input), true)) ? [] : [name]);
26
26
  if (inputs.length > 0) throw new Error(`MCP tool input must be one object with keys, such as a struct: ${inputs.join(", ")} (wrap a union, an array or a scalar in a field, omit input for no arguments, or leave the action out of actions)`);
27
27
  const misplaced = lifted.flatMap(([action, lift]) => isMisplaced(action, lift) ? [action.name] : []);
28
- if (misplaced.length > 0) throw new Error(`MCP media must be the success or an array of it, or a top-level field of a struct success, one, optional or a required array: ${misplaced.join(", ")} (make the image such a field, or give an optional array as a required one, empty when absent; an image in input or an error is not served over MCP, so leave that action out of actions)`);
28
+ if (misplaced.length > 0) throw new Error(`MCP media must be the success or an array of it, a member of a union success whose other members encode to a string, or a top-level field of a struct success, one, optional or a required array: ${misplaced.join(", ")} (make the image such a field, or give an optional array as a required one, empty when absent; an image in input or an error is not served over MCP, so leave that action out of actions)`);
29
29
  };
30
- const nativeInternalErrorText = "Tool execution failed due to an internal server error.";
31
- const textErrorResult = (text) => new McpSchema.CallToolResult({
30
+ const internalErrorResult = new McpSchema.CallToolResult({
32
31
  isError: true,
33
32
  content: [{
34
33
  type: "text",
35
- text
36
- }]
34
+ text: "Tool execution failed due to an internal server error."
35
+ }],
36
+ _meta: { [McpSchema.TOOL_ERROR_META_KEY]: { kind: "internal" } }
37
37
  });
38
38
  const nativeJsonTextOf = (encoded) => encoded === void 0 ? [] : [{
39
39
  type: "text",
@@ -43,13 +43,20 @@ const errorTextOf = (encoded) => {
43
43
  if (Predicate.isString(encoded)) return encoded;
44
44
  return Predicate.hasProperty(encoded, "message") && Predicate.isString(encoded.message) && encoded.message !== "" ? encoded.message : JSON.stringify(encoded);
45
45
  };
46
+ const failureInfoOf = (encoded) => Predicate.hasProperty(encoded, "_tag") && Predicate.isString(encoded._tag) && encoded._tag !== "" ? {
47
+ kind: "failure",
48
+ tag: encoded._tag
49
+ } : { kind: "failure" };
46
50
  const declaredErrorResult = (encoded) => new McpSchema.CallToolResult({
47
51
  isError: true,
48
52
  content: [{
49
53
  type: "text",
50
54
  text: errorTextOf(encoded)
51
55
  }],
52
- _meta: { [errorKey]: encoded }
56
+ _meta: {
57
+ [errorKey]: encoded,
58
+ [McpSchema.TOOL_ERROR_META_KEY]: failureInfoOf(encoded)
59
+ }
53
60
  });
54
61
  const contentBlockOf = ({ kind, field, value }) => ({
55
62
  type: kind,
@@ -68,7 +75,7 @@ const toolOf = (action, outputSchema) => Effect.map(Schema.decodeUnknownEffect(M
68
75
  },
69
76
  _meta: action.mcp._meta === void 0 ? void 0 : { ...action.mcp._meta }
70
77
  }));
71
- const internalError = (cause) => Effect.logError(cause).pipe(Effect.andThen(ErrorReporter.report(cause)), Effect.as(textErrorResult(nativeInternalErrorText)));
78
+ const internalError = (cause) => Effect.logError(cause).pipe(Effect.andThen(ErrorReporter.report(cause)), Effect.as(internalErrorResult));
72
79
  const internalErrorOnDefect = (cause) => Cause.hasDies(cause) ? internalError(cause) : Effect.failCause(cause);
73
80
  const encoder = (schema) => {
74
81
  const encode = Schema.encodeUnknownEffect(Schema.toCodecJson(schema));
@@ -95,11 +102,12 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
95
102
  const call = (input) => asCaller(authentication, action, reported(input));
96
103
  const liftedFieldNames = new Set(media?.fields.map(({ name }) => name));
97
104
  const resultOf = (encoded, success) => {
98
- if (text) return new McpSchema.CallToolResult({
105
+ const answer = text || media?.otherwise !== void 0 ? encoded : void 0;
106
+ if (Predicate.isString(answer)) return new McpSchema.CallToolResult({
99
107
  isError: false,
100
108
  content: [{
101
109
  type: "text",
102
- text: encoded
110
+ text: answer
103
111
  }]
104
112
  });
105
113
  if (media === void 0) return new McpSchema.CallToolResult({
@@ -218,11 +226,6 @@ function layerHttp(apps, { actions, features, path = defaultPath, authentication
218
226
  const middleware = HttpRouter.middleware(Effect.map(providerOf(authentication), (runtime) => (route) => Effect.flatMap(HttpServerRequest.HttpServerRequest, (request) => request.method !== "POST" || required(request.headers) ? runtime.http(readsItsBody(route), false) : Effect.flatMap(namesItsMethod(request), (named) => runtime.http(readsItsBody(route), named)))));
219
227
  return transport.pipe(Layer.provide(middleware.layer));
220
228
  }
221
- const isJsonLine = (line) => Option.isSome(Schema.decodeOption(Schema.fromJsonString(Schema.Json))(line));
222
- const jsonLinesOnly = Layer.effect(Stdio.Stdio, Effect.map(Stdio.Stdio, (stdio) => Stdio.make({
223
- ...stdio,
224
- stdin: stdio.stdin.pipe(Stream.decodeText, Stream.splitLines, Stream.filter(isJsonLine), Stream.map((line) => `${line}\n`), Stream.encodeText)
225
- })));
226
229
  function runStdio(apps, { actions, features, ...options }) {
227
230
  const { apps: selected, events } = selectFrom(apps, actions);
228
231
  assertEventsServable(events.flatMap((app) => app.events));
@@ -234,7 +237,7 @@ function runStdio(apps, { actions, features, ...options }) {
234
237
  ...options,
235
238
  protocols: servingEvents(protocols, serving),
236
239
  registrations
237
- }).pipe(Layer.provide(jsonLinesOnly)), features);
240
+ }), features);
238
241
  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));
239
242
  }
240
243
  export { McpCallError, client, layerHttp, request, runStdio };
@@ -6,7 +6,7 @@ import { assertOnce, heldOnce } from "./contract/names.mjs";
6
6
  import { progressSink } from "./contract/progress.mjs";
7
7
  import { provideServed } from "./contract/serving.mjs";
8
8
  import { toolSuccessOf } from "./contract/stream.mjs";
9
- import { Effect, Schema, SchemaGetter } from "effect";
9
+ import { Effect, Predicate, Schema, SchemaGetter } from "effect";
10
10
  import { Prompt, Tool, Toolkit } from "effect/ai";
11
11
  // src/toolkit/ActionToolkit.ts
12
12
  const annotateIfGiven = (tool, key, value) => value === void 0 ? tool : tool.annotate(key, value);
@@ -34,10 +34,19 @@ const modelOutputOf = (success) => {
34
34
  const lift = liftOf(success);
35
35
  if (lift.fields.length === 0) return;
36
36
  const encodeRest = lift.rest === void 0 ? void 0 : Schema.encodeUnknownSync(Schema.toCodecJson(lift.rest));
37
- return (result) => [...encodeRest === void 0 ? [] : [Prompt.textPart({ text: JSON.stringify(encodeRest(result)) })], ...liftedFrom(lift, result).map(({ value }) => Prompt.filePart({
38
- mediaType: value.mimeType,
39
- data: value.data
40
- }))];
37
+ const encodeOtherwise = lift.otherwise === void 0 ? void 0 : Schema.encodeUnknownSync(Schema.toCodecJson(lift.otherwise));
38
+ const textOf = (result) => {
39
+ const text = encodeOtherwise === void 0 || liftedFrom(lift, result).length > 0 ? void 0 : encodeOtherwise(result);
40
+ return Predicate.isString(text) ? [Prompt.textPart({ text })] : [];
41
+ };
42
+ return (result) => [
43
+ ...textOf(result),
44
+ ...encodeRest === void 0 ? [] : [Prompt.textPart({ text: JSON.stringify(encodeRest(result)) })],
45
+ ...liftedFrom(lift, result).map(({ value }) => Prompt.filePart({
46
+ mediaType: value.mimeType,
47
+ data: value.data
48
+ }))
49
+ ];
41
50
  };
42
51
  const jsonToolOf = (action) => {
43
52
  const success = toolSuccessOf(action.success);
@@ -41,11 +41,26 @@ const liftOf = (success) => {
41
41
  name: void 0,
42
42
  ...whole
43
43
  }],
44
- rest: void 0
44
+ rest: void 0,
45
+ otherwise: void 0
45
46
  };
47
+ if (SchemaAST.isUnion(ast) && ast.encoding === void 0) {
48
+ const members = ast.types.map((member) => [member, wholeSuccessMediaOf(member)]);
49
+ const media = members.flatMap(([, lifted]) => lifted === void 0 ? [] : [{
50
+ name: void 0,
51
+ ...lifted
52
+ }]);
53
+ const others = members.flatMap(([member, lifted]) => lifted === void 0 ? [Schema.make(member)] : []);
54
+ if (media.length > 0) return {
55
+ fields: media,
56
+ rest: void 0,
57
+ otherwise: others.length > 1 ? Schema.Union(others) : others[0]
58
+ };
59
+ }
46
60
  if (!SchemaAST.isObjects(ast) || ast.encoding !== void 0) return {
47
61
  fields: [],
48
- rest: success
62
+ rest: success,
63
+ otherwise: void 0
49
64
  };
50
65
  const fields = ast.propertySignatures.flatMap(({ name, type }) => {
51
66
  const field = mediaFieldOf(type);
@@ -56,13 +71,15 @@ const liftOf = (success) => {
56
71
  });
57
72
  if (fields.length === 0) return {
58
73
  fields,
59
- rest: success
74
+ rest: success,
75
+ otherwise: void 0
60
76
  };
61
77
  const names = new Set(fields.map(({ name }) => name));
62
78
  const rest = ast.propertySignatures.filter(({ name }) => !names.has(name));
63
79
  const { identifier: _identifierOfWholeSuccess, ...annotationsOfRest } = ast.annotations ?? {};
64
80
  return {
65
81
  fields,
82
+ otherwise: void 0,
66
83
  rest: rest.length === 0 && ast.indexSignatures.length === 0 ? void 0 : Schema.make(new SchemaAST.Objects(rest, ast.indexSignatures, annotationsOfRest))
67
84
  };
68
85
  };
@@ -1,8 +1,9 @@
1
1
  import { Schema, SchemaAST } from "effect";
2
2
  /**
3
3
  * An image, a media field of a success: `{ data: Uint8Array, mimeType: string }`, `mimeType` such
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, a toolkit tool
4
+ * as `image/png`. A top-level field of a struct success, one, optional, or a required array, the
5
+ * whole success, one or an array, or a member of a union success whose other members encode to a
6
+ * string, such as a tool answering a file's text or its image: an MCP tool lifts it into an image block of its own, a toolkit tool
6
7
  * into a file part of what its model reads, and every other surface sends it as JSON, the bytes in
7
8
  * base64. `ActionMcp` refuses it anywhere else, and a toolkit sends it there in the JSON.
8
9
  *
@@ -7,8 +7,9 @@ const Media = Schema.Struct({
7
7
  });
8
8
  /**
9
9
  * An image, a media field of a success: `{ data: Uint8Array, mimeType: string }`, `mimeType` such
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, a toolkit tool
10
+ * as `image/png`. A top-level field of a struct success, one, optional, or a required array, the
11
+ * whole success, one or an array, or a member of a union success whose other members encode to a
12
+ * string, such as a tool answering a file's text or its image: an MCP tool lifts it into an image block of its own, a toolkit tool
12
13
  * into a file part of what its model reads, and every other surface sends it as JSON, the bytes in
13
14
  * base64. `ActionMcp` refuses it anywhere else, and a toolkit sends it there in the JSON.
14
15
  *
@@ -30,7 +30,10 @@ export interface Options<E = HttpClientError.HttpClientError, R = never> {
30
30
  readonly baseUrl?: NonNullable<Parameters<typeof HttpApiClient.make>[1]>["baseUrl"];
31
31
  /**
32
32
  * Wraps the native `HttpClient` the calls send with: a bearer token is
33
- * `HttpClient.mapRequest(HttpClientRequest.bearerToken(token))`, and a credential read or
33
+ * `HttpClient.mapRequest(HttpClientRequest.bearerToken(token))`, a credential in the scheme an
34
+ * `Authentication` declares, API key or Basic included,
35
+ * `HttpClient.mapRequest((request) => HttpApiClient.securityEncode(request, Auth.security, credential))`,
36
+ * and a credential read or
34
37
  * refreshed as each request is sent `(client) => HttpClient.mapRequestEffect(client, authorize)`.
35
38
  * A method also fails with what the returned client fails with beyond an `HttpClientError`, as
36
39
  * it is, and requires what it requires.
@@ -21,7 +21,9 @@ export interface ClientOptions<D extends Any | undefined = Any | undefined, E =
21
21
  readonly url?: string;
22
22
  /**
23
23
  * Wraps the native `HttpClient`, as `ActionHttp.client` takes it: a bearer token is
24
- * `HttpClient.mapRequest(HttpClientRequest.bearerToken(token))`.
24
+ * `HttpClient.mapRequest(HttpClientRequest.bearerToken(token))`, and a credential in the scheme
25
+ * an `Authentication` declares
26
+ * `HttpClient.mapRequest((request) => HttpApiClient.securityEncode(request, Auth.security, credential))`.
25
27
  */
26
28
  readonly transformClient?: (client: HttpClient.HttpClient) => HttpClient.HttpClient.With<E, R>;
27
29
  /**
@@ -50,7 +52,7 @@ type Watching<Listed extends Any$2, D, E, R> = [Listed] extends [never] ? unknow
50
52
  * encoded with the action's schema, and the success decoded from its structured content, each
51
53
  * media field from the blocks whose `_meta` names it, a success that is media, or whose
52
54
  * every field is, from its blocks alone, and a success whose schema encodes only to a string
53
- * from its text block. A declared error the tool returns, the action's own or a refusal, is its
55
+ * from its text block; a union of the two from its image blocks when it has any, else its text. A declared error the tool returns, the action's own or a refusal, is its
54
56
  * decoded value, read from the result's `_meta`, and so is a refusal the endpoint's authentication answers
55
57
  * with: a test telling a 401 or 403 from a tool result asserts the status of a request `request`
56
58
  * builds. The argument may be omitted when `{}` is a valid input. Where `contracts` lists event
@@ -48,7 +48,7 @@ const callTool = (client, url, action, success, refusedWith, input, sink) => {
48
48
  const declared = result._meta?.[errorKey];
49
49
  return yield* declared === void 0 ? Effect.fail(undeclared) : failWith(projectedErrors(action), JSON.stringify(declared), undeclared);
50
50
  }
51
- if (lift.fields.length === 0 && isText(success)) {
51
+ if (lift.fields.length === 0 ? isText(success) : lift.otherwise !== void 0 && result.content.every((block) => block.type === "text")) {
52
52
  if (firstText === void 0 || result.structuredContent !== void 0) return yield* callError(method, name, new UnexpectedContent({ body: text }));
53
53
  return yield* Schema.decodeEffect(Schema.toCodecJson(success))(firstText);
54
54
  }
@@ -68,11 +68,12 @@ const holdsMediaAnywhere = (ast) => {
68
68
  }
69
69
  return false;
70
70
  };
71
- const isMisplaced = (action, { rest }) => [
71
+ const isMisplaced = (action, { rest, otherwise }) => [
72
72
  action.input,
73
73
  ...action.error,
74
- ...rest === void 0 ? [] : [rest]
75
- ].some(({ ast }) => holdsMediaAnywhere(ast));
74
+ ...rest === void 0 ? [] : [rest],
75
+ ...otherwise === void 0 ? [] : [otherwise]
76
+ ].some(({ ast }) => holdsMediaAnywhere(ast)) || otherwise !== void 0 && !isText(otherwise);
76
77
  const mediaOf = ({ name, kind, many }, result) => {
77
78
  const values = result.content.flatMap((block) => block.type === kind && block._meta?.["io.github.gjermundgaraba.effect-actions/field"] === name ? [{
78
79
  data: Base64.encode(block.data),
package/docs/ActionMcp.md CHANGED
@@ -72,7 +72,7 @@ A tool is its contract ([Action.md](Action.md#define-a-contract)): a model knows
72
72
 
73
73
  ## Return images and other media
74
74
 
75
- Give the success an `Action.Image` field and return its bytes and MIME type from the handler: `get_camera_snapshot` in [mcp-tools/src/printers/Printers.ts](../examples/mcp-tools/src/printers/Printers.ts); `ActionMcp.client` decodes it back. Where `ActionMcp` refuses one is on `Action.Image`: [kitchen-sink/src/Actions.ts](../examples/kitchen-sink/src/Actions.ts).
75
+ Give the success an `Action.Image` field and return its bytes and MIME type from the handler: `get_camera_snapshot` in [mcp-tools/src/printers/Printers.ts](../examples/mcp-tools/src/printers/Printers.ts); `ActionMcp.client` decodes it back. A tool that answers text or an image, such as one reading a file that may be a picture, takes `Schema.Union([Schema.String, Action.Image])` as its success and returns either. Where `ActionMcp` refuses one is on `Action.Image`: [kitchen-sink/src/Actions.ts](../examples/kitchen-sink/src/Actions.ts).
76
76
 
77
77
  ## Protect tools
78
78
 
@@ -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.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.4` beside `effect@4.1.4`.
11
+ - Type errors inside `effect/*` modules after install, an unmet peer warning for `effect`, such as `found 4.3.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.2.0` beside `effect@4.2.0`.
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,21 +7,21 @@ 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.1.4
10
+ pnpm add @gjermundgaraba/effect-actions effect@~4.2.0
11
11
  ```
12
12
 
13
13
  | Need | Add |
14
14
  | --- | --- |
15
- | Node HTTP server, stdio host or CLI | `@effect/platform-node@~4.1.4` |
16
- | `Stored`'s event logs and idempotency on Node's SQLite, or an entity's storage on Effect's SQL runners | `@effect/sql-sqlite-node@~4.1.4` |
17
- | Tests | `vitest@^5` and `@effect/vitest@~4.1.4`, as dev dependencies |
15
+ | Node HTTP server, stdio host or CLI | `@effect/platform-node@~4.2.0` |
16
+ | `Stored`'s event logs and idempotency on Node's SQLite, or an entity's storage on Effect's SQL runners | `@effect/sql-sqlite-node@~4.2.0` |
17
+ | Tests | `vitest@^5` and `@effect/vitest@~4.2.0`, as dev dependencies |
18
18
  | Type checking | `typescript@^7.0.2`, as a dev dependency |
19
19
  | Node's types, for `node:` imports | `@types/node`, as a dev dependency |
20
20
  | Running a TypeScript entrypoint | `tsx`, as a dev dependency: `node --import tsx <entrypoint>.ts` |
21
21
 
22
- 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
+ The `effect` peer admits the 4.2.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.
23
23
 
24
- Keep the tilde in `package.json`: `^4.1.4`, which npm writes for `effect@4.1.4`, admits a minor release outside the peer range. `npm install effect@~4.1.4` keeps it.
24
+ Keep the tilde in `package.json`: `^4.2.0`, which npm writes for `effect@4.2.0`, admits a minor release outside the peer range. `npm install effect@~4.2.0` keeps it.
25
25
 
26
26
  Node `>=26.13.1`: 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:
27
27
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/effect-actions",
3
- "version": "0.39.1",
3
+ "version": "0.41.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",
@@ -54,14 +54,14 @@
54
54
  "access": "public"
55
55
  },
56
56
  "devDependencies": {
57
- "@clanker-stuff/oxlint-config": "0.5.1",
58
- "@effect/platform-node": "4.1.7",
59
- "@effect/sql-sqlite-node": "4.1.7",
60
- "@effect/tsgo": "0.73.7",
61
- "@effect/vitest": "4.1.7",
57
+ "@clanker-stuff/oxlint-config": "0.6.1",
58
+ "@effect/platform-node": "4.2.0",
59
+ "@effect/sql-sqlite-node": "4.2.0",
60
+ "@effect/tsgo": "0.74.4",
61
+ "@effect/vitest": "4.2.0",
62
62
  "@modelcontextprotocol/client": "2.4.0",
63
- "@types/node": "26.6.6",
64
- "effect": "4.1.7",
63
+ "@types/node": "26.6.11",
64
+ "effect": "4.2.0",
65
65
  "tsx": "4.23.15",
66
66
  "typescript": "7.0.2",
67
67
  "ultracite": "8.3.1",
@@ -70,12 +70,12 @@
70
70
  "vitest": "5.1.1"
71
71
  },
72
72
  "peerDependencies": {
73
- "effect": "~4.1.4"
73
+ "effect": "~4.2.0"
74
74
  },
75
75
  "devEngines": {
76
76
  "packageManager": {
77
77
  "name": "pnpm",
78
- "version": "12.21.0",
78
+ "version": "12.23.0",
79
79
  "onFail": "download"
80
80
  }
81
81
  },