@roll-agent/sdk 0.5.0 → 0.6.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/dist/app-output.d.ts +24 -0
- package/dist/define-agent.d.ts +2 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/types/index.d.ts +5 -0
- package/package.json +4 -3
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type AppOutputContract, type AppOutputDeclaration } from "@roll-agent/protocol/app-output";
|
|
3
|
+
import type { AnyToolDefinition } from "./types/index.ts";
|
|
4
|
+
export declare function prepareAppOutput(tool: AnyToolDefinition): {
|
|
5
|
+
readonly declaration: AppOutputDeclaration;
|
|
6
|
+
readonly contract: AppOutputContract;
|
|
7
|
+
} | undefined;
|
|
8
|
+
export declare function projectAppOutput(schema: z.ZodType, result: unknown): Promise<{
|
|
9
|
+
isError: true;
|
|
10
|
+
_meta: {
|
|
11
|
+
"roll/appOutputStatus": "invalid" | "too_large";
|
|
12
|
+
"roll/executionStatus": string;
|
|
13
|
+
};
|
|
14
|
+
content: [{
|
|
15
|
+
type: "text";
|
|
16
|
+
text: string;
|
|
17
|
+
}];
|
|
18
|
+
} | {
|
|
19
|
+
content: [{
|
|
20
|
+
type: "text";
|
|
21
|
+
text: string;
|
|
22
|
+
}];
|
|
23
|
+
structuredContent: Record<string, unknown>;
|
|
24
|
+
}>;
|
package/dist/define-agent.d.ts
CHANGED
|
@@ -37,6 +37,8 @@ type McpToolResult = {
|
|
|
37
37
|
type: "text";
|
|
38
38
|
text: string;
|
|
39
39
|
}, ...McpToolContentBlock[]];
|
|
40
|
+
structuredContent?: Record<string, unknown>;
|
|
41
|
+
_meta?: Record<string, unknown>;
|
|
40
42
|
};
|
|
41
43
|
export declare function executeToolForMcp(tool: AnyToolDefinition, ctx: AgentContext, params: Record<string, unknown>, signal?: AbortSignal): Promise<McpToolResult>;
|
|
42
44
|
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -7,3 +7,4 @@ export { StructuredToolError, isStructuredToolError } from "./tool-error.ts";
|
|
|
7
7
|
export type { StructuredToolErrorPayload } from "./tool-error.ts";
|
|
8
8
|
export type { AnyToolDefinition, ToolDefinition, AgentDefinition, RunnableAgent, TransportConfig, ListenOptions, ToolResourceAccessMode, ToolResourceHint, ToolResourceHintKind, } from "./types/index.ts";
|
|
9
9
|
export { TOOL_RESOURCE_ACCESS_MODES, TOOL_RESOURCE_HINT_KINDS } from "./types/index.ts";
|
|
10
|
+
export type { AppOutputDeclaration, AppOutputContract } from "@roll-agent/protocol/app-output";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{APP_OUTPUT_META_KEY as e}from"@roll-agent/protocol/app-output";import{AjvJsonSchemaValidator as t}from"@modelcontextprotocol/sdk/validation/ajv";import{isDeepStrictEqual as o}from"node:util";import{z as n}from"zod";import{toJsonSchemaCompat as r}from"@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";import{APP_OUTPUT_LIMITS as s,APP_OUTPUT_STATUS_META_KEY as a,appOutputDeclarationSchema as i,validateAppOutputContract as c}from"@roll-agent/protocol/app-output";function f(e,t=new Set){if(!t.has(e))if(t.add(e),e instanceof n.ZodObject){for(const o of Object.values(e.shape))o instanceof n.ZodType&&f(o,t);e._def.catchall instanceof n.ZodNever||f(e._def.catchall,t)}else if(e instanceof n.ZodArray)f(e.element,t);else if(e instanceof n.ZodOptional||e instanceof n.ZodNullable||e instanceof n.ZodReadonly||e instanceof n.ZodBranded)f(e.unwrap(),t);else if(e instanceof n.ZodUnion)for(const o of e.options)f(o,t);else if(e instanceof n.ZodDiscriminatedUnion)for(const o of e.options)f(o,t);else if(e instanceof n.ZodTuple){for(const o of e.items)f(o,t);e._def.rest&&f(e._def.rest,t)}else if(e instanceof n.ZodRecord)f(e.keySchema,t),f(e.valueSchema,t);else if(e instanceof n.ZodString||e instanceof n.ZodNumber||e instanceof n.ZodBoolean){if(e._def.coerce)throw new Error("appOutput does not support coercion");if(e instanceof n.ZodString)for(const t of e._def.checks)if(["trim","toLowerCase","toUpperCase"].includes(t.kind)||"regex"===t.kind&&""!==t.regex.flags)throw new Error("appOutput cannot represent string transformations or regex flags")}else if(e instanceof n.ZodLiteral){const t=e.value;if(null!==t&&"string"!=typeof t&&"boolean"!=typeof t&&("number"!=typeof t||!Number.isFinite(t)))throw new Error("appOutput requires JSON-compatible literals")}else if(!(e instanceof n.ZodNull||e instanceof n.ZodEnum||e instanceof n.ZodNativeEnum))throw new Error(`appOutput cannot represent ${e.constructor.name} as JSON Schema`)}function p(e){if(!e.appOutput)return;if(!(e.output instanceof n.ZodObject))throw new Error("appOutput requires an object output schema");f(e.output);const o=i.parse(e.appOutput),s=c({...o,outputSchema:r(e.output,{pipeStrategy:"output"})});return(new t).getValidator(s.outputSchema),{declaration:o,contract:s}}function u(e){return{isError:!0,_meta:{[a]:e,"roll/executionStatus":"completed"},content:[{type:"text",text:"Tool execution completed; application output unavailable. Do not repeat the operation."}]}}async function l(e,t){try{const n=await e.safeParseAsync(t);if(!n.success||!o(n.data,t))return u("invalid");const r=JSON.stringify(t);if(void 0===r)return u("invalid");if(Buffer.byteLength(r,"utf8")>s.resultBytes)return u("too_large");const a=JSON.parse(r);return!o(a,t)||"object"!=typeof a||null===a||Array.isArray(a)?u("invalid"):{content:[{type:"text",text:r}],structuredContent:a}}catch{return u("invalid")}}import{createServer as d}from"node:http";import{randomUUID as m}from"node:crypto";import{McpServer as y}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as g}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as w}from"@modelcontextprotocol/sdk/server/streamableHttp.js";var h={debug:0,info:1,warn:2,error:3};function v(e,t="info"){const o=h[t],n=(t,n)=>{if(h[t]<o)return;const r=(new Date).toISOString(),s=t.toUpperCase().padEnd(5);console.error(`${r} [${s}] [${e}] ${n}`)};return{debug:e=>n("debug",e),info:e=>n("info",e),warn:e=>n("warn",e),error:e=>n("error",e)}}import{z as S}from"zod";var x=8;function b(e){let t=e;for(let e=0;e<x;e+=1)if(t instanceof S.ZodEffects)t=t.innerType();else if(t instanceof S.ZodOptional||t instanceof S.ZodNullable||t instanceof S.ZodBranded||t instanceof S.ZodReadonly)t=t.unwrap();else if(t instanceof S.ZodDefault)t=t.removeDefault();else{if(!(t instanceof S.ZodCatch))return t;t=t.removeCatch()}return t}async function Z(e,t){const o=await e.safeParseAsync(t);if(!o.success)throw new Error(`Tool input validation failed: ${O(o.error)}`);return o.data}function O(e){return e.issues.map(e=>{const t=e.path.join(".");return t.length>0?`${t}: ${e.message}`:e.message}).join("; ")}var T=class extends Error{payload;constructor(e){super(e.message),this.name="StructuredToolError",this.payload=e}};function E(e){return e instanceof T||e instanceof Error&&"payload"in e&&j(e.payload)}function j(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;const t=e,o=t.details;return"string"==typeof t.code&&"string"==typeof t.message&&(void 0===o||"object"==typeof o&&null!==o&&!Array.isArray(o))}var N="roll/resourceHints";function $(e){return e??A()??"info"}function A(){const e=process.env.ROLL_AGENT_LOG_LEVEL;if("debug"===e||"info"===e||"warn"===e||"error"===e)return e}function I(e,t,o){return{llm:{generateText:async e=>{try{const t=_((await o.server.createMessage({messages:[{role:"user",content:{type:"text",text:e}}],maxTokens:1024})).content);if(void 0===t)throw new Error("Sampling response did not include text content");return t}catch(e){throw new Error("LLM sampling unavailable. Ensure roll-core client enables sampling capability.",{cause:e})}}},logger:v(e,t)}}function _(e){if("object"==typeof e&&null!==e&&"type"in e&&"text"===e.type&&"text"in e){const t=e.text;return"string"==typeof t?t:void 0}if(Array.isArray(e))for(const t of e){const e=_(t);if(void 0!==e)return e}}function k(e,t={}){return{...e,listen:async o=>{const n=o?.transport??{type:"stdio"},r=$(t.logLevel);"http"===n.type?await H(e,r,n.port,n.host,t.onShutdown):await L(e,r,t.onShutdown)}}}function C(e){let t;const o=o=>{t??=e(o).catch(()=>{process.exit(1)})};process.once("SIGTERM",()=>{o("SIGTERM")}),process.once("SIGINT",()=>{o("SIGINT")})}async function L(e,t,o){const n=new y({name:e.name,version:"0.0.1"}),r=I(e.name,t,n);for(const t of e.tools)J(n,t,r);const s=new g;await n.connect(s),r.logger.info("MCP Server running on stdio");C(async e=>{r.logger.info(`${e} received, shutting down...`),o&&await o(),await n.close(),process.exit(0)})}async function H(e,t,o,n,r){const s=v(e.name,t),a=new Map,i=d(async(o,n)=>{if("/mcp"!==new URL(o.url??"/",`http://${o.headers.host??"localhost"}`).pathname)return n.writeHead(404,{"Content-Type":"application/json"}),void n.end(JSON.stringify({error:"Not found"}));const r="string"==typeof o.headers["mcp-session-id"]?o.headers["mcp-session-id"]:void 0;if(r){const e=a.get(r);if(e){try{await e.transport.handleRequest(o,n)}catch(e){s.error(`Error handling request for session ${r}: ${String(e)}`),n.headersSent||(n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Internal server error"})))}return}return n.writeHead(404,{"Content-Type":"application/json"}),void n.end(JSON.stringify({error:"Session not found"}))}try{const r=new w({sessionIdGenerator:()=>m()}),i=new y({name:e.name,version:"0.0.1"}),c=I(e.name,t,i);for(const t of e.tools)J(i,t,c);r.onclose=()=>{const e=r.sessionId;e&&(a.delete(e),s.info(`Session ${e} closed`))},r.onerror=e=>{s.error(`Transport error (session ${r.sessionId??"unknown"}): ${e.message}`)},await i.connect(r),await r.handleRequest(o,n),r.sessionId&&a.set(r.sessionId,{transport:r,server:i})}catch(e){s.error(`Error creating new session: ${String(e)}`),n.headersSent||(n.writeHead(500,{"Content-Type":"application/json"}),n.end(JSON.stringify({error:"Failed to create session"})))}});i.on("error",e=>{s.error(`HTTP server error: ${e.message}`)});const c=n??"127.0.0.1";i.listen(o,c,()=>{s.info(`MCP Server running on http://${c}:${o}/mcp`)});C(async e=>{s.info(`${e} received, shutting down HTTP server...`),await new Promise(e=>{i.close(()=>e())});const t=[];for(const[,e]of a)t.push(e.server.close());await Promise.all(t),a.clear(),r&&await r(),process.exit(0)})}function J(t,o,n){const r=p(o),s={...o._meta??{},...r?{[e]:r.declaration}:{},...o.resourceHints&&o.resourceHints.length>0?{[N]:o.resourceHints}:{}};t.registerTool(o.name,{description:o.description,inputSchema:b(o.input),...r?{outputSchema:o.output}:{},...o.annotations?{annotations:o.annotations}:{},...Object.keys(s).length>0?{_meta:s}:{}},async(e,t)=>await P(o,n,e,t.signal))}function R(e){if("object"!=typeof e||null===e||Array.isArray(e))return{payload:e,images:[]};const t=e,o=t.mcpImages;if(!Array.isArray(o))return{payload:e,images:[]};const n=o.filter(e=>"object"==typeof e&&null!==e&&"string"==typeof e.data&&"string"==typeof e.mimeType),{mcpImages:r,...s}=t;return{payload:s,images:n}}async function P(e,t,o,n){const r=p(e),s=await Z(e.input,o),a=void 0===n?t:{...t,signal:n};try{const t=await e.execute(s,a);if(r)return await l(e.output,t);const{payload:o,images:n}=R(t);return{content:[{type:"text",text:JSON.stringify(o)},...n.map(e=>({type:"image",data:e.data,mimeType:e.mimeType}))]}}catch(e){if(E(e))return{isError:!0,content:[{type:"text",text:JSON.stringify(e.payload)}]};throw e}}function G(e){return e}var M={read:"read",write:"write"},q={file:"file",browserSession:"browser-session",conversation:"conversation",custom:"custom"};export{T as StructuredToolError,M as TOOL_RESOURCE_ACCESS_MODES,q as TOOL_RESOURCE_HINT_KINDS,v as createAgentLogger,k as defineAgent,G as defineTool,E as isStructuredToolError};
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AppOutputDeclaration } from "@roll-agent/protocol/app-output";
|
|
1
2
|
import type { z } from "zod";
|
|
2
3
|
import type { ToolAnnotations as McpToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
|
|
3
4
|
import type { AgentContext } from "../context.ts";
|
|
@@ -29,6 +30,10 @@ export interface AnyToolDefinition {
|
|
|
29
30
|
readonly output: z.ZodType;
|
|
30
31
|
readonly annotations?: McpToolAnnotations;
|
|
31
32
|
readonly resourceHints?: readonly ToolResourceHint[];
|
|
33
|
+
/** Explicit opt-in to the persistent application result channel. */
|
|
34
|
+
readonly appOutput?: Omit<AppOutputDeclaration, "remoteReadable"> & {
|
|
35
|
+
readonly remoteReadable?: boolean;
|
|
36
|
+
};
|
|
32
37
|
readonly _meta?: Readonly<Record<string, unknown>>;
|
|
33
38
|
readonly execute: (input: never, ctx: AgentContext) => Promise<unknown>;
|
|
34
39
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@roll-agent/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -26,8 +26,9 @@
|
|
|
26
26
|
"node": ">=22.6.0"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
30
|
-
"zod": "^3.25.76"
|
|
29
|
+
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
30
|
+
"zod": "^3.25.76",
|
|
31
|
+
"@roll-agent/protocol": "0.7.0"
|
|
31
32
|
},
|
|
32
33
|
"devDependencies": {
|
|
33
34
|
"@types/node": "^22.0.0"
|