@gjermundgaraba/effect-actions 0.40.0 → 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.
@@ -122,6 +122,7 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
122
122
  *
123
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`.
124
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.
125
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`.
126
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.
127
128
  * - An action answering a stream, `Action.Stream`, answers its elements collected into one array once the stream ends, a success of that array.
@@ -25,7 +25,7 @@ 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
30
  const internalErrorResult = new McpSchema.CallToolResult({
31
31
  isError: true,
@@ -102,11 +102,12 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
102
102
  const call = (input) => asCaller(authentication, action, reported(input));
103
103
  const liftedFieldNames = new Set(media?.fields.map(({ name }) => name));
104
104
  const resultOf = (encoded, success) => {
105
- 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({
106
107
  isError: false,
107
108
  content: [{
108
109
  type: "text",
109
- text: encoded
110
+ text: answer
110
111
  }]
111
112
  });
112
113
  if (media === void 0) return new McpSchema.CallToolResult({
@@ -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
  *
@@ -52,7 +52,7 @@ type Watching<Listed extends Any$2, D, E, R> = [Listed] extends [never] ? unknow
52
52
  * encoded with the action's schema, and the success decoded from its structured content, each
53
53
  * media field from the blocks whose `_meta` names it, a success that is media, or whose
54
54
  * every field is, from its blocks alone, and a success whose schema encodes only to a string
55
- * 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
56
56
  * decoded value, read from the result's `_meta`, and so is a refusal the endpoint's authentication answers
57
57
  * with: a test telling a 401 or 403 from a tool result asserts the status of a request `request`
58
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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/effect-actions",
3
- "version": "0.40.0",
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",