@gjermundgaraba/effect-actions 0.37.0 → 0.38.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.
@@ -117,13 +117,15 @@ type Inferring<D, A extends Pick<Any$1, "caller">> = [D] extends [undefined] ? [
117
117
  * **Gotchas**
118
118
  *
119
119
  * - 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
- * - A declared error is an `isError: true` tool result in a 200 holding its JSON as one text block, with no `structuredContent`; a refusal is answered as `Action.Unauthenticated` and `Action.Forbidden` say.
120
+ * - 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.
121
+ * - 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.
121
123
  * - An action answering a stream, `Action.Stream`, answers its elements collected into one array once the stream ends, a success of that array.
122
- * - 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["effect-actions/progress"]` the value; a call without a token gets none.
124
+ * - 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.
123
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.
124
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.
125
127
  * - 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 an empty 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.
126
- * - A 2025-11-25 or 2025-06-18 client gets `structuredContent` only for a success that is an object: any other success arrives as its text block alone, a string unquoted.
128
+ * - 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.
127
129
  * - 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.
128
130
  * - A request body is read whole, however large, and a 2025 session holds what its `initialize` sent until it ends, so an oversized `initialize` costs memory for that long: limit bodies as `ActionHttp.layer` says.
129
131
  * - An event type named starting with `mcp.`, a prefix MCP keeps for its own events, is refused as the endpoint is made, with `MCP event name starts with "mcp."`.
@@ -13,7 +13,7 @@ import { servingFeeds } from "./contract/webhooks.mjs";
13
13
  import { withStderrConsole } from "./stdio/console.mjs";
14
14
  import { eventSchemasOf, withEvents } from "./mcp/bridge.mjs";
15
15
  import { progressNotifier } from "./mcp/progress.mjs";
16
- import { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, protocols, toolJsonSchema } from "./mcp/protocol.mjs";
16
+ import { defaultPath, errorKey, fieldKey, httpProtocol, isMisplaced, isObjectSchema, isText, protocols, toolJsonSchema } from "./mcp/protocol.mjs";
17
17
  import { client } from "./mcp/client.mjs";
18
18
  import { McpCallError } from "./mcp/reply.mjs";
19
19
  import { request } from "./mcp/request.mjs";
@@ -39,6 +39,18 @@ const nativeJsonTextOf = (encoded) => encoded === void 0 ? [] : [{
39
39
  type: "text",
40
40
  text: JSON.stringify(encoded)
41
41
  }];
42
+ const errorTextOf = (encoded) => {
43
+ if (Predicate.isString(encoded)) return encoded;
44
+ return Predicate.hasProperty(encoded, "message") && Predicate.isString(encoded.message) && encoded.message !== "" ? encoded.message : JSON.stringify(encoded);
45
+ };
46
+ const declaredErrorResult = (encoded) => new McpSchema.CallToolResult({
47
+ isError: true,
48
+ content: [{
49
+ type: "text",
50
+ text: errorTextOf(encoded)
51
+ }],
52
+ _meta: { [errorKey]: encoded }
53
+ });
42
54
  const contentBlockOf = ({ kind, field, value }) => ({
43
55
  type: kind,
44
56
  data: value.data,
@@ -72,7 +84,8 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
72
84
  const lift = liftOf(toolSuccess);
73
85
  const media = lift.fields.length === 0 ? void 0 : lift;
74
86
  const structuredSuccess = media === void 0 ? toolSuccess : media.rest;
75
- const structured = structuredSuccess === void 0 ? void 0 : Schema.toCodecJson(structuredSuccess);
87
+ const text = media === void 0 && isText(toolSuccess);
88
+ const structured = structuredSuccess === void 0 || text ? void 0 : Schema.toCodecJson(structuredSuccess);
76
89
  const outputSchema = structured === void 0 ? void 0 : yield* Schema.decodeUnknownEffect(McpSchema.ToolOutputJson)(toolJsonSchema(structured, false)).pipe(Effect.orDie);
77
90
  const tool = yield* toolOf(action, outputSchema).pipe(Effect.orDie);
78
91
  const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(action.input), inputParseOptions);
@@ -82,6 +95,13 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
82
95
  const call = (input) => asCaller(authentication, action, reported(input));
83
96
  const liftedFieldNames = new Set(media?.fields.map(({ name }) => name));
84
97
  const resultOf = (encoded, success) => {
98
+ if (text) return new McpSchema.CallToolResult({
99
+ isError: false,
100
+ content: [{
101
+ type: "text",
102
+ text: encoded
103
+ }]
104
+ });
85
105
  if (media === void 0) return new McpSchema.CallToolResult({
86
106
  isError: false,
87
107
  structuredContent: encoded,
@@ -107,10 +127,7 @@ const registerTools = Effect.fnUntraced(function* (apps, authentication) {
107
127
  toolName: action.name,
108
128
  description: message
109
129
  }).message })), Effect.flatMap((input) => call(input).pipe(Effect.matchEffect({
110
- onFailure: (error) => Effect.map(encodeFailure(error), (encoded) => new McpSchema.CallToolResult({
111
- isError: true,
112
- content: nativeJsonTextOf(encoded)
113
- })),
130
+ onFailure: (error) => Effect.map(encodeFailure(error), declaredErrorResult),
114
131
  onSuccess: (success) => Effect.map(encodeSuccess(success), (encoded) => resultOf(encoded, success))
115
132
  }))), Effect.catchCause(internalErrorOnDefect))
116
133
  });
@@ -80,7 +80,7 @@ declare const Forbidden_base: Schema.Class<Forbidden, Schema.TaggedStruct<"Forbi
80
80
  * **Gotchas**
81
81
  *
82
82
  * - Over HTTP its JSON with a 403: from authentication before the body is read, from `authorize` or a handler after the input is decoded; on a protected route under Bearer, one naming `scopes` also carries the challenge.
83
- * - Over MCP, from authentication the HTTP 403 before the arguments are decoded; from `authorize` or a handler an `isError: true` tool result holding its JSON as text, in a **200**, not a 403; only on an endpoint under Bearer is a protected tool's refusal naming `scopes` the HTTP 403 with the challenge instead.
83
+ * - Over MCP, from authentication the HTTP 403 before the arguments are decoded; from `authorize` or a handler an `isError: true` tool result, in a **200**, not a 403, whose text is its `message` alone, so a model reads no `scopes` unless the message names them; only on an endpoint under Bearer is a protected tool's refusal naming `scopes` the HTTP 403 with the challenge instead.
84
84
  * - Over RPC the typed failure, never a status or a challenge; on a Toolkit and in a CLI as a declared error.
85
85
  * - From another service's client, such as `ActionHttp.client`, one passed on becomes this server's own refusal: map it to an error the action declares, or to a defect.
86
86
  */
@@ -68,7 +68,7 @@ const ScopeToken = Schema.String.check(Schema.isPattern(scopeToken));
68
68
  * **Gotchas**
69
69
  *
70
70
  * - Over HTTP its JSON with a 403: from authentication before the body is read, from `authorize` or a handler after the input is decoded; on a protected route under Bearer, one naming `scopes` also carries the challenge.
71
- * - Over MCP, from authentication the HTTP 403 before the arguments are decoded; from `authorize` or a handler an `isError: true` tool result holding its JSON as text, in a **200**, not a 403; only on an endpoint under Bearer is a protected tool's refusal naming `scopes` the HTTP 403 with the challenge instead.
71
+ * - Over MCP, from authentication the HTTP 403 before the arguments are decoded; from `authorize` or a handler an `isError: true` tool result, in a **200**, not a 403, whose text is its `message` alone, so a model reads no `scopes` unless the message names them; only on an endpoint under Bearer is a protected tool's refusal naming `scopes` the HTTP 403 with the challenge instead.
72
72
  * - Over RPC the typed failure, never a status or a challenge; on a Toolkit and in a CLI as a declared error.
73
73
  * - From another service's client, such as `ActionHttp.client`, one passed on becomes this server's own refusal: map it to an error the action declares, or to a defect.
74
74
  */
@@ -48,9 +48,10 @@ type Watching<Listed extends Any$2, D, E, R> = [Listed] extends [never] ? unknow
48
48
  * A client of an MCP endpoint served by `layerHttp`, one method per action calling
49
49
  * its tool with one stateless request, as `ActionHttp.client` calls routes: the input is
50
50
  * encoded with the action's schema, and the success decoded from its structured content, each
51
- * media field from the blocks whose `_meta` names it, and a success that is media, or whose
52
- * every field is, from its blocks alone. A declared error the tool returns, the action's own
53
- * or a refusal, is its decoded value, and so is a refusal the endpoint's authentication answers
51
+ * media field from the blocks whose `_meta` names it, a success that is media, or whose
52
+ * 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
54
+ * decoded value, read from the result's `_meta`, and so is a refusal the endpoint's authentication answers
54
55
  * with: a test telling a 401 or 403 from a tool result asserts the status of a request `request`
55
56
  * builds. The argument may be omitted when `{}` is a valid input. Where `contracts` lists event
56
57
  * types, `watch` subscribes to one as `Action.client`'s does, holding `events/stream` open, or
@@ -8,8 +8,8 @@ import { assertOnce } from "../contract/names.mjs";
8
8
  import { elementOf } from "../contract/stream.mjs";
9
9
  import { watching } from "../contract/watch.mjs";
10
10
  import { decodedSink } from "./progress.mjs";
11
- import { defaultPath, unliftedFrom } from "./protocol.mjs";
12
- import { NoReply, NoStructuredContent, ProtocolError, StatusError, UndeclaredError, bodyOf, callError, failWith } from "./reply.mjs";
11
+ import { defaultPath, errorKey, isText, unliftedFrom } from "./protocol.mjs";
12
+ import { NoReply, ProtocolError, StatusError, UndeclaredError, UnexpectedContent, bodyOf, callError, failWith } from "./reply.mjs";
13
13
  import { request } from "./request.mjs";
14
14
  import { transportOf } from "./watch.mjs";
15
15
  import { Effect, Option, Schema, Stream } from "effect";
@@ -42,11 +42,17 @@ const callTool = (client, url, action, success, refusedWith, input, sink) => {
42
42
  if (Option.isNone(reply)) return yield* callError(method, name, new NoReply({ body: text }));
43
43
  if ("error" in reply.value) return yield* callError(method, name, new ProtocolError(reply.value.error));
44
44
  const { result } = reply.value;
45
+ const firstText = textOf(result.content.find((block) => block.type === "text"));
45
46
  if (result.isError === true) {
46
- const error = textOf(result.content.find((block) => block.type === "text")) ?? "";
47
- return yield* failWith(projectedErrors(action), error, callError(method, name, new UndeclaredError({ text: error })));
47
+ const undeclared = callError(method, name, new UndeclaredError({ text: firstText ?? "" }));
48
+ const declared = result._meta?.[errorKey];
49
+ return yield* declared === void 0 ? Effect.fail(undeclared) : failWith(projectedErrors(action), JSON.stringify(declared), undeclared);
48
50
  }
49
- if (result.structuredContent === void 0 && lift.rest !== void 0) return yield* callError(method, name, new NoStructuredContent({ body: text }));
51
+ if (lift.fields.length === 0 && isText(success)) {
52
+ if (firstText === void 0 || result.structuredContent !== void 0) return yield* callError(method, name, new UnexpectedContent({ body: text }));
53
+ return yield* Schema.decodeEffect(Schema.toCodecJson(success))(firstText);
54
+ }
55
+ if (result.structuredContent === void 0 && lift.rest !== void 0) return yield* callError(method, name, new UnexpectedContent({ body: text }));
50
56
  return yield* Schema.decodeUnknownEffect(Schema.toCodecJson(success))(unliftedFrom(lift, result));
51
57
  });
52
58
  };
@@ -2,7 +2,7 @@ import { progressSink } from "../contract/progress.mjs";
2
2
  import { Effect, Option, Schema } from "effect";
3
3
  import { McpSchema } from "effect/ai";
4
4
  // src/mcp/progress.ts
5
- const progressKey = "effect-actions/progress";
5
+ const progressKey = "io.github.gjermundgaraba.effect-actions/progress";
6
6
  const tokenOf = Schema.decodeUnknownOption(McpSchema.ProgressToken);
7
7
  const progressNotifier = (notifications, progress) => Effect.map(Effect.service(McpSchema.McpRequestContext), ({ requestMetadata }) => {
8
8
  const token = tokenOf(requestMetadata?.progressToken);
@@ -45,7 +45,10 @@ const toolJsonSchema = (schema, strict) => {
45
45
  $defs: definitions
46
46
  };
47
47
  };
48
- const fieldKey = "effect-actions/field";
48
+ const fieldKey = "io.github.gjermundgaraba.effect-actions/field";
49
+ const errorKey = "io.github.gjermundgaraba.effect-actions/error";
50
+ /** Whether a success's schema encodes only to a string, which a tool sends as its raw text alone. */
51
+ const isText = (success) => toolJsonSchema(Schema.toCodecJson(success), false)?.["type"] === "string";
49
52
  const partsAndEncodedSideOf = (ast) => [
50
53
  ...SchemaAST.isDeclaration(ast) ? ast.typeParameters : [],
51
54
  ...SchemaAST.isArrays(ast) ? [...ast.elements, ...ast.rest] : [],
@@ -71,7 +74,7 @@ const isMisplaced = (action, { rest }) => [
71
74
  ...rest === void 0 ? [] : [rest]
72
75
  ].some(({ ast }) => holdsMediaAnywhere(ast));
73
76
  const mediaOf = ({ name, kind, many }, result) => {
74
- const values = result.content.flatMap((block) => block.type === kind && block._meta?.["effect-actions/field"] === name ? [{
77
+ const values = result.content.flatMap((block) => block.type === kind && block._meta?.["io.github.gjermundgaraba.effect-actions/field"] === name ? [{
75
78
  data: Base64.encode(block.data),
76
79
  mimeType: block.mimeType
77
80
  }] : []);
@@ -88,4 +91,4 @@ const unliftedFrom = (lift, result) => {
88
91
  return field.name === void 0 || value === void 0 ? [] : [[field.name, value]];
89
92
  })]);
90
93
  };
91
- export { defaultPath, fieldKey, httpProtocol, isMisplaced, isObjectSchema, protocols, toolJsonSchema, unliftedFrom };
94
+ export { defaultPath, errorKey, fieldKey, httpProtocol, isMisplaced, isObjectSchema, isText, protocols, toolJsonSchema, unliftedFrom };
@@ -34,13 +34,17 @@ declare const UndeclaredError_base: Schema.Class<UndeclaredError, Schema.TaggedS
34
34
  }>;
35
35
  /** The tool returned an error whose text decodes as none of the action's declared errors. */
36
36
  export declare class UndeclaredError extends UndeclaredError_base {}
37
- declare const NoStructuredContent_base: Schema.Class<NoStructuredContent, Schema.TaggedStruct<"NoStructuredContent", {
37
+ declare const UnexpectedContent_base: Schema.Class<UnexpectedContent, Schema.TaggedStruct<"UnexpectedContent", {
38
38
  readonly body: Schema.String;
39
39
  }>, import("effect/Cause").YieldableError & {
40
40
  readonly brand: unique symbol;
41
41
  }>;
42
- /** The tool returned a result without the structured content its action's success needs. */
43
- export declare class NoStructuredContent extends NoStructuredContent_base {}
42
+ /**
43
+ * The tool returned a result whose content does not fit its action's success: no structured
44
+ * content where the success needs it, or, for a success whose schema encodes only to a string,
45
+ * no text block, or structured content beside it.
46
+ */
47
+ export declare class UnexpectedContent extends UnexpectedContent_base {}
44
48
  declare const FrameTooLarge_base: Schema.Class<FrameTooLarge, Schema.TaggedStruct<"FrameTooLarge", {
45
49
  readonly maxEventSize: Schema.Int;
46
50
  }>, import("effect/Cause").YieldableError & {
@@ -58,7 +62,7 @@ export declare class FrameTooLarge extends FrameTooLarge_base {}
58
62
  declare const McpCallError_base: Schema.Class<McpCallError, Schema.TaggedStruct<"McpCallError", {
59
63
  readonly method: Schema.String;
60
64
  readonly target: Schema.String;
61
- readonly reason: Schema.Union<readonly [typeof StatusError, typeof ProtocolError, typeof NoReply, typeof UndeclaredError, typeof NoStructuredContent, typeof FrameTooLarge]>;
65
+ readonly reason: Schema.Union<readonly [typeof StatusError, typeof ProtocolError, typeof NoReply, typeof UndeclaredError, typeof UnexpectedContent, typeof FrameTooLarge]>;
62
66
  readonly message: Schema.String;
63
67
  }>, import("effect/Cause").YieldableError & {
64
68
  readonly brand: unique symbol;
@@ -18,8 +18,12 @@ var ProtocolError = class extends Schema.TaggedError()("ProtocolError", {
18
18
  var NoReply = class extends Schema.TaggedError()("NoReply", { body: Schema.String }) {};
19
19
  /** The tool returned an error whose text decodes as none of the action's declared errors. */
20
20
  var UndeclaredError = class extends Schema.TaggedError()("UndeclaredError", { text: Schema.String }) {};
21
- /** The tool returned a result without the structured content its action's success needs. */
22
- var NoStructuredContent = class extends Schema.TaggedError()("NoStructuredContent", { body: Schema.String }) {};
21
+ /**
22
+ * The tool returned a result whose content does not fit its action's success: no structured
23
+ * content where the success needs it, or, for a success whose schema encodes only to a string,
24
+ * no text block, or structured content beside it.
25
+ */
26
+ var UnexpectedContent = class extends Schema.TaggedError()("UnexpectedContent", { body: Schema.String }) {};
23
27
  /**
24
28
  * The endpoint's event stream held more than `maxEventSize` characters with no frame ending, the
25
29
  * most a client holds while it waits for one.
@@ -34,7 +38,7 @@ const Reason = Schema.Union([
34
38
  ProtocolError,
35
39
  NoReply,
36
40
  UndeclaredError,
37
- NoStructuredContent,
41
+ UnexpectedContent,
38
42
  FrameTooLarge
39
43
  ]);
40
44
  const sentenceOf = Match.typeTags()({
@@ -42,7 +46,7 @@ const sentenceOf = Match.typeTags()({
42
46
  ProtocolError: ({ code, message }) => `failed with ${code}: ${message}`,
43
47
  NoReply: ({ body }) => `had no reply: ${body}`,
44
48
  UndeclaredError: ({ text }) => `returned an error: ${text}`,
45
- NoStructuredContent: ({ body }) => `returned no structured content: ${body}`,
49
+ UnexpectedContent: ({ body }) => `returned content that does not fit its success: ${body}`,
46
50
  FrameTooLarge: ({ maxEventSize }) => `sent more than ${maxEventSize} characters of an event stream with no frame ending`
47
51
  });
48
52
  /**
@@ -85,4 +89,4 @@ const bodyOf = (method, name, response, sink) => isEventStream(response) ? Strea
85
89
  onSome: (value) => sink === void 0 ? Effect.succeed(false) : Effect.as(sink.progress(value), false)
86
90
  }))) : Effect.map(response.text, (text) => [text]);
87
91
  const failWith = (errors, text, otherwise) => Schema.decodeEffect(Schema.fromJsonString(Schema.toCodecJson(Schema.Union(errors))))(text).pipe(Effect.mapError(() => otherwise), Effect.flatMap(Effect.fail));
88
- export { FrameTooLarge, McpCallError, NoReply, NoStructuredContent, ProtocolError, StatusError, UndeclaredError, bodyOf, callError, failWith, framesOf, isEventStream };
92
+ export { FrameTooLarge, McpCallError, NoReply, ProtocolError, StatusError, UndeclaredError, UnexpectedContent, bodyOf, callError, failWith, framesOf, isEventStream };
package/docs/ActionMcp.md CHANGED
@@ -67,6 +67,7 @@ A tool is its contract ([Action.md](Action.md#define-a-contract)): a model knows
67
67
 
68
68
  - Constrain in the schema what a model may send: `PrinterId` in [mcp-tools/src/printers/Printers.ts](../examples/mcp-tools/src/printers/Printers.ts). Which checks reach the listed schema is on `Action.Options.input`.
69
69
  - A model acts on a declared error's `message`, so write it for the model: [mcp-tools/src/platform/print-farm.ts](../examples/mcp-tools/src/platform/print-farm.ts).
70
+ - A model reads a success whose schema is a string as it is, and an object or a `NullOr` of a string as escaped JSON, so return text it reads or copies, such as a file's lines or a command's output, as a string success: `greet` in [quickstart/src/greeting/Greeting.ts](../examples/quickstart/src/greeting/Greeting.ts). What each shape sends is on `layerHttp`.
70
71
  - `ActionMcp.Options`'s `actions` lists the tools, and only listed actions must suit MCP: [kitchen-sink/src/Actions.ts](../examples/kitchen-sink/src/Actions.ts). Leave out an action a model should not call, or one that takes a secret ([Action.md](Action.md#define-a-contract)).
71
72
 
72
73
  ## Return images and other media
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gjermundgaraba/effect-actions",
3
- "version": "0.37.0",
3
+ "version": "0.38.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",