@outfitter/mcp 0.2.0 → 0.4.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
@@ -54,18 +54,122 @@ Creates an MCP server instance.
54
54
 
55
55
  ```typescript
56
56
  interface McpServerOptions {
57
- name: string; // Server name for MCP handshake
58
- version: string; // Server version (semver)
59
- logger?: Logger; // Optional structured logger
57
+ name: string; // Server name for MCP handshake
58
+ version: string; // Server version (semver)
59
+ logger?: Logger; // Optional structured logger (BYO)
60
+ defaultLogLevel?: McpLogLevel | null; // Default log forwarding level
60
61
  }
61
62
 
62
63
  const server = createMcpServer({
63
64
  name: "my-server",
64
65
  version: "1.0.0",
65
- logger: createLogger({ name: "mcp" }),
66
66
  });
67
+
68
+ // If `logger` is omitted, Outfitter logger factory defaults are used.
69
+ ```
70
+
71
+ ### Bring Your Own Logger (BYO)
72
+
73
+ `createMcpServer` accepts any logger implementing the shared `Logger` contract.
74
+ This lets you use the default Outfitter backend or a custom backend adapter.
75
+
76
+ #### Outfitter factory backend
77
+
78
+ ```typescript
79
+ import { createOutfitterLoggerFactory } from "@outfitter/logging";
80
+
81
+ const loggerFactory = createOutfitterLoggerFactory();
82
+ const server = createMcpServer({
83
+ name: "my-server",
84
+ version: "1.0.0",
85
+ logger: loggerFactory.createLogger({
86
+ name: "mcp",
87
+ context: { surface: "mcp" },
88
+ }),
89
+ });
90
+ ```
91
+
92
+ #### Custom adapter backend
93
+
94
+ ```typescript
95
+ import {
96
+ createLoggerFactory,
97
+ type Logger,
98
+ type LoggerAdapter,
99
+ } from "@outfitter/contracts";
100
+
101
+ type BackendOptions = { write: (line: string) => void };
102
+
103
+ const adapter: LoggerAdapter<BackendOptions> = {
104
+ createLogger(config) {
105
+ const write = config.backend?.write ?? (() => {});
106
+ const createMethod = (level: string): Logger["info"] =>
107
+ ((message: string) => {
108
+ write(`[${level}] ${config.name}: ${message}`);
109
+ }) as Logger["info"];
110
+
111
+ return {
112
+ trace: createMethod("trace"),
113
+ debug: createMethod("debug"),
114
+ info: createMethod("info"),
115
+ warn: createMethod("warn"),
116
+ error: createMethod("error"),
117
+ fatal: createMethod("fatal"),
118
+ child: (childContext) =>
119
+ adapter.createLogger({
120
+ ...config,
121
+ context: { ...(config.context ?? {}), ...childContext },
122
+ }),
123
+ };
124
+ },
125
+ };
126
+
127
+ const loggerFactory = createLoggerFactory(adapter);
128
+ const server = createMcpServer({
129
+ name: "my-server",
130
+ version: "1.0.0",
131
+ logger: loggerFactory.createLogger({
132
+ name: "mcp",
133
+ backend: { write: (line) => console.log(line) },
134
+ }),
135
+ });
136
+ ```
137
+
138
+ ### Log Forwarding
139
+
140
+ MCP servers can forward log messages to the connected client. The default log level is resolved from environment configuration:
141
+
142
+ **Precedence** (highest wins):
143
+ 1. `OUTFITTER_LOG_LEVEL` environment variable
144
+ 2. `options.defaultLogLevel`
145
+ 3. `OUTFITTER_ENV` profile defaults (`"debug"` in development, `null` otherwise)
146
+ 4. `null` (no forwarding)
147
+
148
+ ```typescript
149
+ const server = createMcpServer({
150
+ name: "my-server",
151
+ version: "1.0.0",
152
+ // Forwarding level auto-resolved from OUTFITTER_ENV
153
+ });
154
+
155
+ // With OUTFITTER_ENV=development → forwards at "debug"
156
+ // With OUTFITTER_ENV=production → no forwarding (null)
157
+ // With OUTFITTER_LOG_LEVEL=error → forwards at "error"
67
158
  ```
68
159
 
160
+ Set `defaultLogLevel: null` to explicitly disable forwarding regardless of environment. The MCP client can always override via `logging/setLevel`.
161
+
162
+ #### `sendLogMessage(level, data, loggerName?)`
163
+
164
+ Send a log message to the connected MCP client.
165
+
166
+ ```typescript
167
+ server.sendLogMessage("info", "Indexing complete", "my-server");
168
+ server.sendLogMessage("warning", { message: "Rate limited", retryAfter: 30 });
169
+ ```
170
+
171
+ Only sends if the message level meets or exceeds the current client log level threshold.
172
+
69
173
  ### defineTool(definition)
70
174
 
71
175
  Helper for defining typed tools with better type inference.
@@ -86,7 +190,7 @@ const getUserTool = defineTool({
86
190
  handler: async (input, ctx) => {
87
191
  const user = await db.users.find(input.userId);
88
192
  if (!user) {
89
- return Result.err(new NotFoundError("user", input.userId));
193
+ return Result.err(NotFoundError.create("user", input.userId));
90
194
  }
91
195
  return Result.ok(user);
92
196
  },
@@ -255,8 +359,74 @@ for (const tool of coreTools) {
255
359
  }
256
360
  ```
257
361
 
362
+ ## Tool Annotations
363
+
364
+ Use `TOOL_ANNOTATIONS` presets to declare tool behavior hints without manually specifying all four booleans:
365
+
366
+ ```typescript
367
+ import { defineTool, TOOL_ANNOTATIONS } from "@outfitter/mcp";
368
+
369
+ // Use a preset directly
370
+ const listTool = defineTool({
371
+ name: "list-items",
372
+ description: "List all items",
373
+ inputSchema: z.object({}),
374
+ annotations: TOOL_ANNOTATIONS.readOnly,
375
+ handler: async (input, ctx) => { /* ... */ },
376
+ });
377
+
378
+ // Spread and override for edge cases
379
+ const searchTool = defineTool({
380
+ name: "search",
381
+ description: "Search external APIs",
382
+ inputSchema: z.object({ q: z.string() }),
383
+ annotations: { ...TOOL_ANNOTATIONS.readOnly, openWorldHint: true },
384
+ handler: async (input, ctx) => { /* ... */ },
385
+ });
386
+ ```
387
+
388
+ | Preset | readOnly | destructive | idempotent | openWorld |
389
+ |--------|----------|-------------|------------|-----------|
390
+ | `readOnly` | true | false | true | false |
391
+ | `write` | false | false | false | false |
392
+ | `writeIdempotent` | false | false | true | false |
393
+ | `destructive` | false | true | true | false |
394
+ | `openWorld` | false | false | false | true |
395
+
396
+ For multi-action tools, use the most conservative union of hints. Per-action annotations are an MCP spec limitation.
397
+
398
+ ### adaptHandler
399
+
400
+ When your handler returns domain errors that extend `Error` but not `OutfitterError`, use `adaptHandler` instead of an unsafe cast:
401
+
402
+ ```typescript
403
+ import { adaptHandler, defineTool } from "@outfitter/mcp";
404
+
405
+ const tool = defineTool({
406
+ name: "my-tool",
407
+ inputSchema: z.object({ id: z.string() }),
408
+ handler: adaptHandler(myDomainHandler),
409
+ });
410
+ ```
411
+
258
412
  ## Transport Helpers
259
413
 
414
+ ### wrapToolResult / wrapToolError
415
+
416
+ Format handler output as MCP tool responses. Useful when building custom transport layers or testing:
417
+
418
+ ```typescript
419
+ import { wrapToolResult, wrapToolError } from "@outfitter/mcp";
420
+
421
+ // Wrap a plain value as MCP tool content
422
+ const response = wrapToolResult({ count: 42 });
423
+ // { content: [{ type: "text", text: '{"count":42}' }] }
424
+
425
+ // Wrap an error with isError flag
426
+ const errorResponse = wrapToolError(new Error("not found"));
427
+ // { content: [{ type: "text", text: "not found" }], isError: true }
428
+ ```
429
+
260
430
  ### connectStdio
261
431
 
262
432
  Connect server to stdio transport for Claude Desktop integration.
@@ -357,6 +527,10 @@ Config location:
357
527
  - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
358
528
  - Linux: `~/.config/claude/claude_desktop_config.json`
359
529
 
530
+ ## Upgrading
531
+
532
+ Run `outfitter update --guide` for version-specific migration instructions, or check the [migration docs](https://github.com/outfitter-dev/outfitter/tree/main/plugins/outfitter/shared/migrations) for detailed upgrade steps.
533
+
360
534
  ## Related Packages
361
535
 
362
536
  - [@outfitter/contracts](../contracts/README.md) — Result types and error taxonomy
@@ -0,0 +1,4 @@
1
+ import { BuildMcpToolsOptions, buildMcpTools } from "./shared/@outfitter/mcp-a0cgfsnw";
2
+ import "./shared/@outfitter/mcp-h2twz77x";
3
+ import "./shared/@outfitter/mcp-cqpyer9m";
4
+ export { buildMcpTools, BuildMcpToolsOptions };
@@ -0,0 +1,11 @@
1
+ // @bun
2
+ import {
3
+ buildMcpTools
4
+ } from "./shared/@outfitter/mcp-9whem1wr.js";
5
+ import"./shared/@outfitter/mcp-k8r6kefr.js";
6
+ import"./shared/@outfitter/mcp-fjtxsa0x.js";
7
+ import"./shared/@outfitter/mcp-9m5hs2z0.js";
8
+ import"./shared/@outfitter/mcp-f91wbr49.js";
9
+ export {
10
+ buildMcpTools
11
+ };
@@ -0,0 +1,4 @@
1
+ import { ConfigAction, ConfigStore, ConfigToolInput, ConfigToolOptions, ConfigToolResponse, CoreToolDefinition, CoreToolsOptions, DocsSection, DocsToolEntry, DocsToolInput, DocsToolOptions, DocsToolResponse, NormalizedQueryInput, QueryToolInput, QueryToolOptions, QueryToolResponse, createCoreTools, defineConfigTool, defineDocsTool, defineQueryTool } from "./shared/@outfitter/mcp-dwd800vf";
2
+ import "./shared/@outfitter/mcp-h2twz77x";
3
+ import "./shared/@outfitter/mcp-cqpyer9m";
4
+ export { defineQueryTool, defineDocsTool, defineConfigTool, createCoreTools, QueryToolResponse, QueryToolOptions, QueryToolInput, NormalizedQueryInput, DocsToolResponse, DocsToolOptions, DocsToolInput, DocsToolEntry, DocsSection, CoreToolsOptions, CoreToolDefinition, ConfigToolResponse, ConfigToolOptions, ConfigToolInput, ConfigStore, ConfigAction };
@@ -0,0 +1,13 @@
1
+ // @bun
2
+ import {
3
+ createCoreTools,
4
+ defineConfigTool,
5
+ defineDocsTool,
6
+ defineQueryTool
7
+ } from "./shared/@outfitter/mcp-zv3ej45k.js";
8
+ export {
9
+ defineQueryTool,
10
+ defineDocsTool,
11
+ defineConfigTool,
12
+ createCoreTools
13
+ };
package/dist/index.d.ts CHANGED
@@ -2,6 +2,32 @@ import { ActionRegistry, ActionSurface, AnyActionSpec } from "@outfitter/contrac
2
2
  import { Handler, HandlerContext, Logger, OutfitterError, Result, TaggedErrorClass } from "@outfitter/contracts";
3
3
  import { z } from "zod";
4
4
  /**
5
+ * @outfitter/mcp - Logging Bridge
6
+ *
7
+ * Maps Outfitter log levels to MCP log levels for
8
+ * server-to-client log message notifications.
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ /**
13
+ * MCP log levels as defined in the MCP specification.
14
+ * Ordered from least to most severe.
15
+ */
16
+ type McpLogLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency";
17
+ /**
18
+ * Outfitter log levels.
19
+ */
20
+ type OutfitterLogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
21
+ /**
22
+ * Map an Outfitter log level to the corresponding MCP log level.
23
+ */
24
+ declare function mapLogLevelToMcp(level: OutfitterLogLevel): McpLogLevel;
25
+ /**
26
+ * Check whether a message at the given level should be emitted
27
+ * based on the client-requested threshold.
28
+ */
29
+ declare function shouldEmitLog(messageLevel: McpLogLevel, threshold: McpLogLevel): boolean;
30
+ /**
5
31
  * Configuration options for creating an MCP server.
6
32
  *
7
33
  * @example
@@ -28,9 +54,22 @@ interface McpServerOptions {
28
54
  version: string;
29
55
  /**
30
56
  * Optional logger instance for server logging.
31
- * If not provided, a no-op logger is used.
57
+ * If not provided, the server uses the Outfitter logger factory defaults.
32
58
  */
33
59
  logger?: Logger;
60
+ /**
61
+ * Default MCP log level for client-facing log forwarding.
62
+ *
63
+ * Precedence (highest wins):
64
+ * 1. `OUTFITTER_LOG_LEVEL` environment variable
65
+ * 2. This option
66
+ * 3. Environment profile (`OUTFITTER_ENV`)
67
+ * 4. `null` (no forwarding until client opts in)
68
+ *
69
+ * Set to `null` to explicitly disable forwarding regardless of environment.
70
+ * The MCP client can always override via `logging/setLevel`.
71
+ */
72
+ defaultLogLevel?: McpLogLevel | null;
34
73
  }
35
74
  /**
36
75
  * Behavioral hints for MCP tools.
@@ -51,6 +90,57 @@ interface ToolAnnotations {
51
90
  openWorldHint?: boolean;
52
91
  }
53
92
  /**
93
+ * Common annotation presets for MCP tools.
94
+ *
95
+ * Use these as a starting point and spread-override individual hints:
96
+ *
97
+ * ```typescript
98
+ * annotations: { ...TOOL_ANNOTATIONS.readOnly, openWorldHint: true }
99
+ * ```
100
+ *
101
+ * For multi-action tools (e.g., a single tool with read and write actions),
102
+ * use the most conservative union of hints — if any action is destructive,
103
+ * mark the whole tool as destructive. Per-action annotations are an MCP spec
104
+ * limitation; presets + spread cover most edge cases.
105
+ */
106
+ declare const TOOL_ANNOTATIONS: {
107
+ /** Read-only, safe to call repeatedly. */
108
+ readonly readOnly: {
109
+ readonly readOnlyHint: true;
110
+ readonly destructiveHint: false;
111
+ readonly idempotentHint: true;
112
+ readonly openWorldHint: false;
113
+ };
114
+ /** Creates or updates state, not destructive. */
115
+ readonly write: {
116
+ readonly readOnlyHint: false;
117
+ readonly destructiveHint: false;
118
+ readonly idempotentHint: false;
119
+ readonly openWorldHint: false;
120
+ };
121
+ /** Idempotent write (PUT-like). */
122
+ readonly writeIdempotent: {
123
+ readonly readOnlyHint: false;
124
+ readonly destructiveHint: false;
125
+ readonly idempotentHint: true;
126
+ readonly openWorldHint: false;
127
+ };
128
+ /** Deletes or permanently modifies data. */
129
+ readonly destructive: {
130
+ readonly readOnlyHint: false;
131
+ readonly destructiveHint: true;
132
+ readonly idempotentHint: true;
133
+ readonly openWorldHint: false;
134
+ };
135
+ /** Interacts with external systems (APIs, network). */
136
+ readonly openWorld: {
137
+ readonly readOnlyHint: false;
138
+ readonly destructiveHint: false;
139
+ readonly idempotentHint: false;
140
+ readonly openWorldHint: true;
141
+ };
142
+ };
143
+ /**
54
144
  * Definition of an MCP tool that can be invoked by clients.
55
145
  *
56
146
  * Tools are the primary way clients interact with MCP servers.
@@ -560,6 +650,16 @@ interface McpServer {
560
650
  */
561
651
  setLogLevel?(level: string): void;
562
652
  /**
653
+ * Send a log message to connected clients.
654
+ * Filters by the client-requested log level threshold.
655
+ * No-op if no SDK server is bound or if the message is below the threshold.
656
+ *
657
+ * @param level - MCP log level for the message
658
+ * @param data - Log data (string, object, or any serializable value)
659
+ * @param loggerName - Optional logger name for client-side filtering
660
+ */
661
+ sendLogMessage(level: McpLogLevel, data: unknown, loggerName?: string): void;
662
+ /**
563
663
  * Bind the SDK server instance for notifications.
564
664
  * Called internally by the transport layer.
565
665
  * @param sdkServer - The MCP SDK Server instance
@@ -598,6 +698,28 @@ interface McpHandlerContext extends HandlerContext {
598
698
  /** Progress reporter, present when client provides a progressToken */
599
699
  progress?: ProgressReporter;
600
700
  }
701
+ /**
702
+ * Adapt a handler with a domain error type for use with MCP tools.
703
+ *
704
+ * MCP tool definitions constrain `TError extends OutfitterError`. When your
705
+ * handler returns domain-specific errors that extend `Error` but not
706
+ * `OutfitterError`, use this function instead of an unsafe cast:
707
+ *
708
+ * ```typescript
709
+ * import { adaptHandler } from "@outfitter/mcp";
710
+ *
711
+ * const tool = defineTool({
712
+ * name: "my-tool",
713
+ * inputSchema: z.object({ id: z.string() }),
714
+ * handler: adaptHandler(myDomainHandler),
715
+ * });
716
+ * ```
717
+ */
718
+ declare function adaptHandler<
719
+ TInput,
720
+ TOutput,
721
+ TError extends Error
722
+ >(handler: (input: TInput, ctx: HandlerContext) => Promise<Result<TOutput, TError>>): Handler<TInput, TOutput, OutfitterError>;
601
723
  interface BuildMcpToolsOptions {
602
724
  readonly includeSurfaces?: readonly ActionSurface[];
603
725
  }
@@ -697,32 +819,6 @@ interface CoreToolsOptions {
697
819
  type NormalizedQueryInput = Required<Pick<QueryToolInput, "q">> & Omit<QueryToolInput, "q">;
698
820
  type CoreToolDefinition = ToolDefinition<DocsToolInput, DocsToolResponse> | ToolDefinition<ConfigToolInput, ConfigToolResponse> | ToolDefinition<QueryToolInput, QueryToolResponse>;
699
821
  declare function createCoreTools(options?: CoreToolsOptions): CoreToolDefinition[];
700
- /**
701
- * @outfitter/mcp - Logging Bridge
702
- *
703
- * Maps Outfitter log levels to MCP log levels for
704
- * server-to-client log message notifications.
705
- *
706
- * @packageDocumentation
707
- */
708
- /**
709
- * MCP log levels as defined in the MCP specification.
710
- * Ordered from least to most severe.
711
- */
712
- type McpLogLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency";
713
- /**
714
- * Outfitter log levels.
715
- */
716
- type OutfitterLogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
717
- /**
718
- * Map an Outfitter log level to the corresponding MCP log level.
719
- */
720
- declare function mapLogLevelToMcp(level: OutfitterLogLevel): McpLogLevel;
721
- /**
722
- * Check whether a message at the given level should be emitted
723
- * based on the client-requested threshold.
724
- */
725
- declare function shouldEmitLog(messageLevel: McpLogLevel, threshold: McpLogLevel): boolean;
726
822
  import { z as z2 } from "zod";
727
823
  /**
728
824
  * JSON Schema representation.
@@ -889,6 +985,22 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
889
985
  import { CallToolResult } from "@modelcontextprotocol/sdk/types";
890
986
  type McpToolResponse = CallToolResult;
891
987
  /**
988
+ * Wrap a handler success value into an MCP CallToolResult.
989
+ *
990
+ * If the value is already a valid McpToolResponse (has a `content` array),
991
+ * it is returned as-is. Otherwise it is wrapped in a text content block.
992
+ * Plain objects are also attached as `structuredContent` for SDK clients
993
+ * that support structured output.
994
+ */
995
+ declare function wrapToolResult(value: unknown): McpToolResponse;
996
+ /**
997
+ * Wrap an error into an MCP CallToolResult with `isError: true`.
998
+ *
999
+ * Serializes the error (preserving `_tag`, `message`, `code`, `context` if
1000
+ * present) and wraps it as a text content block.
1001
+ */
1002
+ declare function wrapToolError(error: unknown): McpToolResponse;
1003
+ /**
892
1004
  * Create an MCP SDK server from an Outfitter MCP server.
893
1005
  */
894
1006
  declare function createSdkServer(server: McpServer): Server;
@@ -896,4 +1008,4 @@ declare function createSdkServer(server: McpServer): Server;
896
1008
  * Connect an MCP server over stdio transport.
897
1009
  */
898
1010
  declare function connectStdio(server: McpServer, transport?: StdioServerTransport): Promise<Server>;
899
- export { zodToJsonSchema, shouldEmitLog, mapLogLevelToMcp, defineTool, defineResourceTemplate, defineResource, defineQueryTool, definePrompt, defineDocsTool, defineConfigTool, createSdkServer, createMcpServer, createCoreTools, connectStdio, buildMcpTools, ToolDefinition, ToolAnnotations, TextResourceContent, SerializedTool, ResourceTemplateReadHandler, ResourceTemplateDefinition, ResourceReadHandler, ResourceDefinition, ResourceContent, QueryToolResponse, QueryToolOptions, QueryToolInput, PromptResult, PromptMessageContent, PromptMessage, PromptHandler, PromptDefinition, PromptArgument, ProgressReporter, McpToolResponse, McpServerOptions, McpServer, McpLogLevel, McpHandlerContext, McpError, JsonSchema, InvokeToolOptions, DocsToolResponse, DocsToolOptions, DocsToolInput, DocsToolEntry, DocsSection, CoreToolsOptions, ContentAnnotations, ConfigToolResponse, ConfigToolOptions, ConfigToolInput, ConfigStore, ConfigAction, CompletionResult, CompletionRef, CompletionHandler, BuildMcpToolsOptions, BlobResourceContent };
1011
+ export { zodToJsonSchema, wrapToolResult, wrapToolError, shouldEmitLog, mapLogLevelToMcp, defineTool, defineResourceTemplate, defineResource, defineQueryTool, definePrompt, defineDocsTool, defineConfigTool, createSdkServer, createMcpServer, createCoreTools, connectStdio, buildMcpTools, adaptHandler, ToolDefinition, ToolAnnotations, TextResourceContent, TOOL_ANNOTATIONS, SerializedTool, ResourceTemplateReadHandler, ResourceTemplateDefinition, ResourceReadHandler, ResourceDefinition, ResourceContent, QueryToolResponse, QueryToolOptions, QueryToolInput, PromptResult, PromptMessageContent, PromptMessage, PromptHandler, PromptDefinition, PromptArgument, ProgressReporter, McpToolResponse, McpServerOptions, McpServer, McpLogLevel, McpHandlerContext, McpError, JsonSchema, InvokeToolOptions, DocsToolResponse, DocsToolOptions, DocsToolInput, DocsToolEntry, DocsSection, CoreToolsOptions, ContentAnnotations, ConfigToolResponse, ConfigToolOptions, ConfigToolInput, ConfigStore, ConfigAction, CompletionResult, CompletionRef, CompletionHandler, BuildMcpToolsOptions, BlobResourceContent };