From 32a96abfc7eea4d804c064c603c239ec2786f1ca Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Wed, 11 Nov 2026 07:42:56 +0000 Subject: [PATCH] sync: update skills from runtypelabs/core@e214275 --- skills/runtype-admin/SKILL.md | 30 ++-- skills/runtype-build-product/SKILL.md | 21 ++- skills/runtype-external-agents/SKILL.md | 23 ++- skills/runtype-persona/SKILL.md | 46 +++-- .../references/webmcp-authoring.md | 149 +++++++++++++++ skills/runtype-sdk-marathon/SKILL.md | 7 +- skills/runtype-templates/SKILL.md | 2 - skills/runtype/SKILL.md | 28 ++- skills/runtype/references/mcp-tools.md | 42 +++-- skills/runtype/references/persona-widget.md | 169 +++++++++++++----- skills/runtype/references/primitives.md | 19 +- skills/runtype/references/recipes.md | 113 ++++++++---- skills/runtype/references/surfaces.md | 60 ++++--- skills/tool-design-composition/SKILL.md | 23 +-- skills/tool-design-errors/SKILL.md | 28 +-- skills/tool-design-execution/SKILL.md | 7 +- skills/tool-design-interface/SKILL.md | 39 +++- skills/tool-design-output/SKILL.md | 16 +- skills/tool-design-security/SKILL.md | 72 +++++--- skills/tool-design/SKILL.md | 65 ++++--- skills/tool-design/references/checklist.md | 4 +- .../tool-design/references/pattern-index.md | 11 ++ 22 files changed, 719 insertions(+), 255 deletions(-) create mode 100644 skills/runtype-persona/references/webmcp-authoring.md diff --git a/skills/runtype-admin/SKILL.md b/skills/runtype-admin/SKILL.md index 51d0308..b0693be 100644 --- a/skills/runtype-admin/SKILL.md +++ b/skills/runtype-admin/SKILL.md @@ -1,8 +1,6 @@ --- name: runtype-admin description: 'Inspect, debug, or manage a live Runtype account through MCP or CLI; mutate only within the requested scope.' -user-invocable: true -argument-hint: '[live account operation or debugging task]' --- # Runtype Admin @@ -15,12 +13,12 @@ workspace unless you run it against a disposable test account. Runtype has two hosted MCP servers. Both accept browser sign-in on the first call, or a Runtype API key sent as `Authorization: Bearer `. -| Server | URL | Tools | -| ------------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Standard MCP | `https://api.runtype.com/v1/mcp/protocol` | One named tool per operation, such as `get_me`, `list_agents`, and `list_runs` | -| Code Mode MCP | `https://code.runtype.com/mcp` | `search`, `execute`, `get_platform_documentation`, `search_documentation`, `get_build_instructions`, `generate_persona_embed_code`, `get_persona_theme_reference` | +| Server | URL | Tools | +| ------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Standard MCP | `https://api.runtype.com/v1/mcp/protocol` | One named tool per operation, such as `get_me`, `list_agents`, and `list_runs` | +| Code Mode MCP | `https://code.runtype.com/mcp` | `search`, `execute`, `get_platform_documentation`, `search_documentation`, `get_build_instructions`, `generate_persona_embed_code`, `get_persona_theme_reference`, `submit_feedback` | -To check which server is connected, look at the tool list. Code Mode lists only the seven +To check which server is connected, look at the tool list. Code Mode lists only the eight tools in the table. Call `get_me` (on Code Mode, `execute` with `async (runtype) => runtype.getMe()`) to confirm the organization before you change anything. @@ -67,6 +65,10 @@ Discover before you act: Surfaces belong to a product. List or change them with the product ID in hand. +When the server lists `delegate_to_runtype`, delegate debugging that needs trace, fix, +and verify, and audits that page across many entities: the digest keeps large payloads +out of your context. Single lookups and edits to a known id are faster as direct calls. + Use `list_model_configs` to see which models the account can run. `list_available_models` is the platform catalog: its `isEnabled` and `isDefault` fields are always null or false, so it cannot tell you whether a model is enabled. @@ -217,9 +219,17 @@ permission is missing, or request a new key: 1. Call `request_api_key` with the narrowest `permissions` that cover the task and a specific `reason`. Keep the returned `codeVerifier`. It cannot be recovered. -2. Wait for a person to approve the request in the dashboard. -3. Redeem it with `runtype api-keys claim --verifier `, or with - `claim_api_key` using the default `delivery: "secret"`. +2. Wait for a person to approve the request in the dashboard. Do not guess when they decide. + With a shell, run + `RUNTYPE_KEY_REQUEST_VERIFIER= runtype api-keys claim --wait` in + the background (older CLIs: `--verifier `). It exits once the request is + decided and writes the key file on approval. +3. Without a shell, call `wait_for_api_key_decision` with the request id. It never claims + the key and never needs the verifier. Or call `wait_for_event` with + `runtype.api_key_request.decided`, arguments `{ requestId }` and cursor `"0"`; if + nothing arrives by the request's `expiresAt`, call `claim_api_key` once to read the + outcome and stop. Then redeem with `claim_api_key` using the default + `delivery: "secret"`. Redeem within 10 minutes of approval. Never print the key into the conversation. diff --git a/skills/runtype-build-product/SKILL.md b/skills/runtype-build-product/SKILL.md index c93def2..2fe7625 100644 --- a/skills/runtype-build-product/SKILL.md +++ b/skills/runtype-build-product/SKILL.md @@ -1,8 +1,6 @@ --- name: runtype-build-product description: 'Build, deploy, validate, or modify Runtype-hosted AI products, agents, flows, tools, surfaces, schedules, and eval suites, including from example templates.' -user-invocable: true -argument-hint: '[product idea or build task]' --- # Runtype Build Product @@ -17,6 +15,20 @@ If the Runtype MCP tools are not available, run `runtype install-mcp` for the cu agent harness. Until the tools appear, call them through the CLI with `runtype mcp tools` and `runtype mcp call `. For sign-in and account setup, use the `runtype` skill. +## Delegate or drive + +If the Runtype MCP server lists `delegate_to_runtype`, hand it the build when the work +stays inside the Runtype account and takes four or more dependent calls (build, validate, +test-run). On a host that runs it as an MCP task (Claude Code's main conversation), three +calls is enough. Put the goal, every decision and target id, and the acceptance check in +`task` up front, relay the `task_url`, and verify anything the digest marks untested. + +Drive the steps yourself (below) when the change is one or two calls or an edit to a +known id, when the user wants to steer each step, when the result feeds code you are +writing, or when it needs local files, secrets, provider keys, or client tokens. The +delegate cannot see or create those. Only the self-driven path needs +`get_build_instructions`. + ## Required first calls Before designing or creating resources: @@ -26,8 +38,9 @@ Before designing or creating resources: - Capability scoping: `get_build_instructions(task="explain-capabilities")`. For a product build, pass `focus` as a comma-separated list when the product clearly -needs one of these areas: `commerce`, `embed`, `subagents`, `skills`, `search`, -`retrieval`, `decision-models`, or `extraction-models`. The response includes those +needs one of these areas: `commerce`, `embed`, `embed-fullscreen`, `subagents`, +`skills`, `search`, `retrieval`, `decision-models`, `extraction-models`, +`operational-design`, `agent-design`, or `prompt-authoring`. The response includes those full guides instead of pointers to them. Then fetch only the `get_platform_documentation` topics the task needs: diff --git a/skills/runtype-external-agents/SKILL.md b/skills/runtype-external-agents/SKILL.md index b7961b4..42f839f 100644 --- a/skills/runtype-external-agents/SKILL.md +++ b/skills/runtype-external-agents/SKILL.md @@ -1,8 +1,6 @@ --- name: runtype-external-agents -description: 'Connect agents that run outside Runtype (Flue, Cloudflare Agents SDK, Vercel AI SDK, LangGraph, OpenAI Agents SDK, Mastra, OpenClaw, Hermes, Pi, custom loops) through OpenTelemetry/OTLP trace export or an A2A or runtype-stream endpoint, to get runs, traces, eval capture, Persona chat, or surfaces; not Runtype-hosted execution.' -user-invocable: true -argument-hint: '[framework and what you want from Runtype: traces, evals, chat UI]' +description: 'Connect agents that run outside Runtype (Flue, Cloudflare Agents SDK, Vercel AI SDK, LangGraph, OpenAI Agents SDK, Mastra, OpenClaw, Hermes, Pi, Pydantic AI, custom loops) through OpenTelemetry/OTLP trace export or an A2A or runtype-stream endpoint, to get runs, traces, eval capture, Persona chat, or surfaces; not Runtype-hosted execution.' --- # Runtype for agents that run elsewhere @@ -41,7 +39,8 @@ Capability matrix to state plainly: `RUNTYPE_CAPTURE_CONTENT=true` for OpenClaw and Pi or `RUNTYPE_OTEL_CAPTURE_CONTENT=true` for Hermes. If the plugin receives no content, the run has no transcript to capture as an eval case. The Pi durable - binding sends content unless `content: false`. + binding sends content unless `content: false`, and the Pydantic AI adapter unless + `content=False`. - Eval **re-run** (`run_eval_suite`) needs Runtype to be able to call the agent. An `external` agent over A2A works (recorded-tool replay cases are skipped). `runtype-stream` endpoints are not eval targets. Telemetry-only runs cannot be re-run. @@ -157,6 +156,20 @@ pi-durable and `PiHarness` are experimental/beta upstream. Report each Pi run through one producer only, or Runtype counts its tokens twice. Neither binding makes the agent callable from Runtype. +**Pydantic AI (`runtype-pydantic-ai`, PyPI).** Supports `pydantic-ai` 1.90+ and 2.x and +sends OTLP itself; do not add an exporter. `pip install runtype-pydantic-ai`, set +`RUNTYPE_API_KEY` (`TELEMETRY:WRITE`) and `RUNTYPE_AGENT_ID`, then call +`runtype_pydantic_ai.instrument()` once at startup; every `Agent` in the process is traced. +`RUNTYPE_OTLP_URL` overrides the full trace URL. With Logfire, call `instrument()` after +`logfire.configure()`, or pass `runtype_pydantic_ai.span_processor()` in +`additional_span_processors`; any instrumentation format from 2 up works. Each top-level run +is one Runtype run (`invoke_agent`, `chat`, `execute_tool`); a sub-agent called from a tool +stays in the outer run. `instrument(agent_ids={...})` maps agent names to Runtype agents. +Content is on by default, including any personal data in prompts; `content=False` or +`ContentOptions` (per-kind switches, `max_chars`, `redact`) narrow it. Spans export in +batches; call `force_flush()` on the returned handle in tests and short-lived handlers. +**Connect an agent** has a **Pydantic AI** chip that creates the agent and key. + **Flue on Node, Cloud Run, or another host.** Point exactly one Flue instrumentation at Runtype. Two would double the tokens and cost. @@ -248,7 +261,7 @@ inside `externalConfig` are the same. - `retryCount` (0 to 10; default 3) retries the connection only, never a stream that has started. - `framework` is a descriptive label (`flue`, `langchain`, `vercel_ai`, `crewai`, - `cloudflare`, `autogen`, or `custom`). It does not change the wire protocol. + `cloudflare`, `autogen`, `mastra`, or `custom`). It does not change the wire protocol. **Where to register.** The dashboard's **Connect External** tab on the new-agent page registers A2A endpoints only. Register a `runtype-stream` agent with `create_agent` or diff --git a/skills/runtype-persona/SKILL.md b/skills/runtype-persona/SKILL.md index 19c53ae..1331ea3 100644 --- a/skills/runtype-persona/SKILL.md +++ b/skills/runtype-persona/SKILL.md @@ -1,8 +1,6 @@ --- name: runtype-persona description: 'Embed, theme, or debug a Runtype Persona chat widget on a website: client tokens, embed snippets, fullscreen assistant layouts, WebMCP page tools, and browser-side chat integrations.' -user-invocable: true -argument-hint: '[Persona widget or chat UI task]' --- # Runtype Persona @@ -68,9 +66,11 @@ Common wrong answers: `@runtype/persona`, `Persona.mount()`, `window.Persona`, ### Load from cdn.runtype.com -When you load Persona from a CDN, use `cdn.runtype.com`. Pages published with the -`publish_page` tool load scripts only from `cdn.runtype.com`, and scripts from other CDNs -fail without an error. On a page that +When you load Persona from a CDN, use `cdn.runtype.com`. Pages published with +`builtin:publish_page` (run it through `execute_tool`) load scripts only from +`cdn.runtype.com` and block inline scripts. Scripts from other CDNs and inline init code +fail without an error, so use the script-installer form with `data-*` attributes there. On +a page that Runtype deploys, replace `latest` with the current published version, for example `https://cdn.runtype.com/persona/PERSONA_VERSION/install.global.js`, so a new release does not change the widget under your deployed page. Pin the version in the script URL, never @@ -99,7 +99,7 @@ as a `version` or `cdn` key in `data-config`. version requires exactly one agent in `agentIds`. A token with no target resolves like any run that names no version, so depending on your organization's live-default setting, a saved agent edit can reach the widget immediately. -4. Generate embed code with `generate_persona_embed_code`. +4. Generate embed code with `generate_persona_embed_code`, then add `future: { v5Defaults: true }` to the widget config to use the V5 default styles. Under V5, the artifact pane is on by default; set `features.artifacts.enabled` to `false` to turn it off. For a coordinated look without hand-written tokens, set the top-level `brand` option (`accent`, `neutral`, `font`, `radius`, `density`, `elevation`). Explicit `theme` values still win. 5. For consumer-facing widgets, hide tool calls and reasoning by default. 6. For internal or debug widgets, expose useful traces intentionally. 7. For custom themes, set explicit high-contrast component tokens and verify header, @@ -136,6 +136,12 @@ and layout-specific token choices. ## Local Tools +Before designing or auditing page tools, read +[`webmcp-authoring.md`](references/webmcp-authoring.md). Use its +journey, trust, confirmation, and evaluation checklist alongside the platform +configuration below. Upstream WebMCP skills supplement these rules; they do not +override Runtype authorization or Persona's compatibility contracts. + Use browser-side local tools when the assistant needs to read page state or trigger UI actions that are only available in the front end. For Persona widgets, these are WebMCP page tools registered on `document.modelContext` and admitted by the chat surface's @@ -162,6 +168,9 @@ Required WebMCP setup: - Register page tools on `document.modelContext` in the host page, for example with `registerTool(...)`. Persona collects them on each turn and runs returned `webmcp:` calls in the browser. +- Install `@mcp-b/webmcp-polyfill` before you register, or check that + `document.modelContext` exists first. It is undefined on a browser without native + support, and Persona installs its fallback only at the first dispatch. - Create the client token with `product_surface_id` set to the `chat` surface, and include the embedding page origin in `allowed_origins`. A token that is not bound to the surface drops every page tool. `product_surface_id` is fixed at creation, so recreate an @@ -171,13 +180,30 @@ Required WebMCP setup: skip approval only for safe read-only tools, and `webmcp.onConfirm` only when the host page needs custom confirmation UI. The widget-side `webmcp.allowlist` is a convenience filter, not a security boundary. +- List consequential tools in `requireConfirmFor` so they always confirm, for example + `["checkout_*", "delete_*"]`. Put the list on the surface as + `behavior.webmcp.requireConfirmFor`; Persona reads it from `/v1/client/init` and merges + it with any widget-side `webmcp.requireConfirmFor`. A matching tool always shows the + approval bubble, even when `autoApprove` returns `true` or the call is a read-only voice + call. A custom `onConfirm` receives `info.confirmRequired: true` for a matching tool and + must not auto-approve it. Patterns match the bare tool name, and `*` matches any run of + characters. - Set the `chat` surface `behavior.webmcp.enabled` to `true`. - Add origin-scoped `behavior.webmcp.allowlist` rules for page tools that should be callable, for example `{ origin: "https://store.example.com", tools: ["search_*"] }`. - The server enforces only `enabled` and `allowlist`. `behavior.webmcp.requireConfirmFor` - (for example `["checkout_*"]`) forces Persona's confirmation and is not a security - boundary: chat dispatch does not enforce it, and the voice direct route never picks a - listed tool. + The server enforces only `enabled` and `allowlist`. `requireConfirmFor` is client-side + confirmation, not a security boundary: chat dispatch does not enforce it, so put every + tool that must never run in the allowlist decision, not only in `requireConfirmFor`. The + voice direct route never picks a listed tool. +- To run page tools one at a time, set `webmcp.execution` to `"sequential"`. The default is + `"parallel"`. +- Each page-tool call has a 30-second timeout. Cancellation is cooperative, so honor the + abort signal. +- Persona truncates a page-tool result above 64 KB and adds a visible marker. It treats + every `webmcp:` result as untrusted, whatever the tool's hints say. +- A custom `webmcp.onConfirm` takes full control of confirmation. Persona consults + `webmcp.autoApprove` only on its default confirmation UI, and never for a tool that + matches `requireConfirmFor`. - After real traffic, open the surface's **WebMCP** section in the dashboard to review discovered tools and observed origins. Discovery records the offered page tools before allowlist filtering. diff --git a/skills/runtype-persona/references/webmcp-authoring.md b/skills/runtype-persona/references/webmcp-authoring.md new file mode 100644 index 0000000..5d6b792 --- /dev/null +++ b/skills/runtype-persona/references/webmcp-authoring.md @@ -0,0 +1,149 @@ +# Design and verify WebMCP page tools + +Use this guide when an assistant needs state or UI that exists only in the +browser. Keep backend work in server-side tools. Read `persona-embed` for the +current client-token, surface, and widget configuration before writing an embed. + +Browser support on 2026-11-05: Chrome origin trial 149 to 162, Edge origin trial from 150, no signal from Firefox or Safari. + +## Install WebMCP before you register + +`document.modelContext` is undefined on a browser without native support until +something installs it. Persona installs its own fallback only at the first +dispatch, and only when `webmcp.enabled` is set, so it cannot cover registration +at page load. + +1. Add `@mcp-b/webmcp-polyfill` to the app and call `installWebMCP()` before you + register. It keeps native support and does nothing on an insecure page. +2. Check that `document.modelContext` exists before each registration, and skip + registration if it does not. + +Persona uses an installed context and does not load its fallback. Persona reads +tools at the start of each turn, so a tool registered after a turn starts misses +that turn. For a full sample, see +[Recipe 10](https://github.com/runtypelabs/skills/blob/main/skills/runtype/references/recipes.md#recipe-10-browser-side-page-tools-for-an-embedded-assistant-webmcp). + +## Design the user journey first + +1. Describe the user's goal and starting state, including authentication, + selected items, open forms, and unsaved changes. +2. Role-play a successful conversation and an ambiguous request. Decide where + the assistant must ask for clarification or hand control to the user. +3. Give each tool one distinct capability. Describe what it does and when to + choose it. Keep navigation separate from an action that commits a purchase, + sends a message, publishes content, or deletes data. +4. Register tools only while their page state exists. Remove owned + registrations with an `AbortController` when the component unmounts. +5. Validate arguments at runtime, recheck the current resource and permissions, + honor cancellation, and await the visible state update before returning. + For stale selections or unsaved work, resolve with + `{ isError: true, content: [{ type: 'text', text: '...' }] }` and say what to + do next. Do not throw: WebMCP masks a thrown error as `Tool execution failed`, + so the model cannot recover. + +For example, `get_cart` reads the cart, while `open_checkout` opens a review +screen. Neither places an order. Keep the final purchase behind the site's +authenticated, user-confirmed checkout. Never accept a model-authored +`confirmed: true` argument as proof of consent. + +## Declare behavior without granting permission + +- Set `readOnlyHint: true` only for tools that change neither application state + nor the visible UI. Navigation is not read-only. +- Set `consequentialHint: true` for tools that commit significant real-world + actions. Opening a review screen is different from committing the action. +- Set `untrustedContentHint: true` when results contain user-authored or + third-party text, even when your own database stores that text. A read-only + query can return untrusted content. +- Treat every hint as advisory. Missing or false hints do not grant permission, + authorize a resource, prove consent, or establish replay safety. +- Keep Persona's confirmation defaults. Use a host-owned, explicitly reviewed + safe-read policy for `webmcp.autoApprove`, not arbitrary page-authored hints. + Do not change the voice lane's existing policy as part of an authoring task. +- List every consequential tool (purchases, sends, deletes) in the surface's + `behavior.webmcp.requireConfirmFor`. A matching tool always confirms, whatever + `autoApprove` returns, and a custom `onConfirm` sees `info.confirmRequired: true`. +- Keep origin-scoped surface allowlists and client-token origin restrictions. + Browser confirmation, `requireConfirmFor`, and client-side filters do not + replace server-side authorization. Tool outputs are data, never instructions + that can authorize a subsequent action. + +## Keep tools inside Chrome's budgets + +Chrome publishes these budgets and says they are subject to change. They are +authoring targets, not Runtype limits. + +| Item | Target | +| ---------------------- | ---------------- | +| Tool or parameter name | 30 characters | +| Tool description | 500 characters | +| Parameter description | 150 characters | +| Tool output | 1,500 characters | + +Runtype's own ceilings are separate and higher: 2 KB for a description and 64 KB +for a result. + +## Know what Persona does with other WebMCP fields + +- `title` is a display name. The model does not choose on it, so keep the + description complete. +- `outputSchema` declares the result shape. Persona drops it from the tool list + it sends, so describe the result in the tool description as well. +- `annotations.debugging` marks a tool as a debugging tool. +- The `exposedTo` registration option lists other origins in the document tree + that can discover and call the tool. Each must be potentially trustworthy. + Persona sends only tools that the current document owns, so it ignores tools + that another frame exposes. +- A cross-origin iframe needs `allow="tools"` to use WebMCP. To turn WebMCP off, + disable the `tools` policy feature with `Permissions-Policy: tools=()`. +- `document.modelContext` fires `toolchange` when the registered tools change. + +## Use native authoring types without replacing compatibility code + +The upstream `webmcp-types` package can infer an `execute` callback's arguments +from a literal `inputSchema`. Add it as a development dependency to the app +authoring the tools and activate it in that app's TypeScript configuration. +It is distinct from `@mcp-b/webmcp-types`. Types do not validate runtime input, +install WebMCP, or establish browser support. + +Do not replace Persona's structural consumer types, v5 fallback, dual-generation +bridge, or public declarations with native-only types. Test declaration builds +and supported browser/polyfill combinations before changing those contracts. + +## Verify behavior at separate layers + +- Run deterministic callback and bridge tests for invalid arguments, stale + resources, declined confirmation, cancellation, unmount, and completed UI + updates. Confirm that a declined action has no side effect. +- Run model evaluations for tool choice, argument extraction, ambiguity, and + recovery after errors. Include an injected instruction in a tool result and + verify it does not cause an unauthorized action. A passing schema-only + evaluation does not prove approval enforcement or prompt-injection safety. +- Inspect tools on every relevant route and state in a native WebMCP browser + and through Persona's supported polyfill paths. Missing browser support is + not evidence that the app registers no tools. +- To inspect tools in Chrome, turn on `chrome://flags/#enable-webmcp-testing`. + Then use the experimental WebMCP pane in the DevTools Application panel (it + also needs `#devtools-webmcp-support`) or the Model Context Tool Inspector + extension. +- To run tool-choice evaluations, use the `webmcp-evals` npm package. +- To audit a page, run the experimental Lighthouse agentic browsing category. It + needs Chrome 150 or later, and its WebMCP audits need a trial registration. +- To test with real visitors, register the site for an origin trial. Chrome and + Edge each need their own token. + +Use synthetic data. Keep provider keys server-side, opt into paid evaluations, +and record the model, runner version, run count, and failures. Do not describe +unrun model evaluations as passing. + +## Further reading + +- [Google's WebMCP authoring skill](https://github.com/GoogleChromeLabs/webmcp-tools/tree/main/webmcp-skills) + provides journey design, role-play, and evaluation workflows. Adapt it to the + policies above. +- [Chrome's guide to secure WebMCP tools](https://developer.chrome.com/docs/ai/webmcp/secure-tools) +- [Native WebMCP types](https://github.com/webmachinelearning/webmcp-types) +- [Persona's typed tools and evaluation example](https://github.com/runtypelabs/persona/tree/main/examples/webmcp-typed-tools) + +This is coding-agent guidance. It is not an A2A `AgentSkill` or a deployed +Runtype Agent Skill bundle. diff --git a/skills/runtype-sdk-marathon/SKILL.md b/skills/runtype-sdk-marathon/SKILL.md index c55683d..d366e06 100644 --- a/skills/runtype-sdk-marathon/SKILL.md +++ b/skills/runtype-sdk-marathon/SKILL.md @@ -1,8 +1,6 @@ --- name: runtype-sdk-marathon description: 'Build source-controlled Runtype workflows with the SDK or CLI: config-as-code deploys from CI (ensure), save-and-run flows (upsert), long-running or multi-session agent runs with Marathon (runtype marathon or runtype agents task), and Marathon playbooks.' -user-invocable: true -argument-hint: '[SDK, CLI, or Marathon task]' --- # Runtype SDK and Marathon @@ -30,7 +28,8 @@ Code-first modes: - **Ensure (config-as-code)**: converge a definition from your repo onto Runtype at deploy time without running it. Ensure never deletes a resource, and agents, flows, and skills keep a version of each change. The SDK has `ensure` for flows, agents, tools, skills, - evals, products, surfaces, and client tokens; `evals.ensure` replaces the suite's cases. + evals, products, surfaces, client tokens, collections, schedules, and question sets. + `evals.ensure` replaces the suite's cases. The CLI has `runtype agents ensure ` for a JSON agent definition; add `--expect-no-changes` to fail a CI job on drift. - **Virtual**: the definition is supplied per execution without creating a saved agent or @@ -139,7 +138,7 @@ and model compatibility at startup. Models: `--model` sets the model for the run, `--planning-model` and `--execution-model` set it per phase, and `--fallback-model` is used when the primary model fails. Use routed -model IDs such as `claude-sonnet-5` or `claude-haiku-4-5`. For `--max-tokens` and +model IDs such as `claude-sonnet-5` or `claude-haiku-5-5`. For `--max-tokens` and `--temperature`, a playbook milestone value beats the CLI flag, and the CLI flag beats the playbook-level default. diff --git a/skills/runtype-templates/SKILL.md b/skills/runtype-templates/SKILL.md index 378d541..39389d5 100644 --- a/skills/runtype-templates/SKILL.md +++ b/skills/runtype-templates/SKILL.md @@ -1,8 +1,6 @@ --- name: runtype-templates description: 'Create, validate, or share distributable Runtype Full Product Object (FPO) templates with import-time variables and pending secrets, or install a product from a runtype.com example, a use.runtype.com/now link, or a template URL.' -user-invocable: true -argument-hint: '[FPO or template task]' --- # Runtype Templates diff --git a/skills/runtype/SKILL.md b/skills/runtype/SKILL.md index d745dc0..bafa9c0 100644 --- a/skills/runtype/SKILL.md +++ b/skills/runtype/SKILL.md @@ -1,8 +1,6 @@ --- name: runtype description: 'Scope a Runtype project or set up platform access; route implementation to the relevant Runtype skill.' -user-invocable: true -argument-hint: '[Runtype goal or setup question]' --- # Runtype @@ -57,9 +55,20 @@ your session. A written configuration does not prove that the connection is acti `runtype api-keys request --name --scopes --reason ` with the narrowest scopes the task needs. The user approves the request in the dashboard, and the CLI writes the key to a local key file. From MCP, call `request_api_key`, keep the - `codeVerifier` it returns, and redeem the approved request with `claim_api_key`. Its - default delivery stores the key as a Runtype secret and returns only a `{{secret:KEY}}` - reference, so the key is never shown in the conversation. + `codeVerifier` it returns, and redeem the approved request with `claim_api_key`. Do not + guess when the user decides: with a shell, run + `RUNTYPE_KEY_REQUEST_VERIFIER= runtype api-keys claim --wait` in the + background; it exits once the request is decided. Otherwise call + `wait_for_api_key_decision` with the request id (it never needs the verifier), or + `wait_for_event` with `runtype.api_key_request.decided`, arguments `{ requestId }` and + cursor `"0"`; if no event arrives by the request's `expiresAt`, call `claim_api_key` once + and stop. Redeem within 10 minutes of approval. Its default delivery stores the key as a Runtype secret and returns only a `{{secret:KEY}}` + reference, so the key is never shown in the conversation. When the key must be collected + on a machine with no Runtype login (a fresh sandbox, for example), file the request with + `--allow-unauthenticated-claim` (MCP `allow_unauthenticated_claim: true`) and redeem it + there with `RUNTYPE_KEY_REQUEST_VERIFIER= runtype api-keys claim `. + The key is limited to scopes you already hold and lasts at most 7 days. Treat the + verifier like the key itself. - **MCP.** Run `runtype install-mcp` for the current coding assistant, follow the action or restart it reports, then confirm the account with `runtype auth whoami --no-tty`. @@ -94,7 +103,7 @@ Use this routing table instead of loading every Runtype detail into context: this coding-assistant skill. Read `get_platform_documentation(topic="agent-skills")`. - Surface: where users or machines reach the product, such as `chat`, `api`, `mcp`, `mcp_code`, `webhook`, `email`, `slack`, `schedule`, `sms`, `imessage`, `discord`, - `whatsapp`, `telegram`, `messaging`, `a2a`, and `hosted-page`. For the current list, + `whatsapp`, `telegram`, `a2a`, `chrome_extension`, and `hosted-page`. For the current list, read `get_platform_documentation(topic="surface-types")`. - Record: Runtype state and agent memory. Keep the source of truth for data that already lives in another system there. @@ -103,9 +112,10 @@ Use this routing table instead of loading every Runtype detail into context: the dashboard also cover routing and channel formatting end to end. - FPO template: the portable distribution format for a product. -When a product has multiple capabilities on one conversational surface, Runtype can -provision an orchestrator that routes each incoming message to the right capability. -Surfaces and capabilities are many-to-many. +When a product has multiple capabilities on one `chat` surface, set +`behavior.mode: "multi_capability"` to route each message to the right capability. The +default mode sends every message to one capability. Messaging channels choose a capability +without a mode. Surfaces and capabilities are many-to-many. ## Reference files diff --git a/skills/runtype/references/mcp-tools.md b/skills/runtype/references/mcp-tools.md index b563b65..144b13b 100644 --- a/skills/runtype/references/mcp-tools.md +++ b/skills/runtype/references/mcp-tools.md @@ -27,6 +27,7 @@ Prefer live tool discovery and `get_platform_documentation` when available; this - [Models](#models) - [Persona widget tokens](#persona-widget-tokens) - [Sandboxes](#sandboxes) +- [Delegation](#delegation-flag-gated-enabledelegatetoruntype) - [Platform docs](#platform-docs) - [Quick selection guide](#quick-selection-guide) @@ -201,15 +202,18 @@ Collections register a record type, optionally with a metadata schema: `list_col ## Tracing, logs, costs -| Tool | Use | -| ----------------------- | ------------------------------------------------- | -| `trace_execution` | Structured trace tree for a single execution | -| `trace_conversation` | Trace spanning multiple turns | -| `list_logs` | Query persisted logs | -| `get_log_stats` | Aggregated counts by level/category + time-series | -| `get_batch_cost` | Total cost for a batch execution | -| `get_batch_record_cost` | One record's cost within a batch | -| `get_record_costs` | Per-record cost by model | +| Tool | Use | +| ----------------------- | ----------------------------------------------------------------------------- | +| `trace_execution` | Structured trace tree for a single execution | +| `trace_conversation` | Trace spanning multiple turns | +| `list_logs` | Query persisted logs | +| `get_log_stats` | Aggregated counts by level/category + time-series | +| `query_traces` | Group runs by agent, model, stop reason, day…; rates, percentiles, sample ids | +| `read_trace_slice` | Bounded span window of one trace, content on demand | +| `compare_trace` | Diff two runs' tool sequences, or two cohorts | +| `get_batch_cost` | Total cost for a batch execution | +| `get_batch_record_cost` | One record's cost within a batch | +| `get_record_costs` | Per-record cost by model | ## Batches and evals @@ -338,6 +342,16 @@ Bring-your-own provider credentials: `list_provider_keys`, `create_provider_key` `extend_asset_expiry` extends a preview page published by the `builtin:publish_page` tool, keeping its URL. +## Delegation (flag-gated: `enableDelegateToRuntype`) + +| Tool | Use | +| --------------------- | ------------------------------------------------------------------------------------------------- | +| `delegate_to_runtype` | Hand a multi-step task to Runtype's in-account operator agent; streams progress, returns a digest | +| `check_delegation` | Long-poll a running delegation for events since `after` | +| `cancel_delegation` | Stop a running delegation; completed changes stay | + +When the account has the flag, the server instructions recommend delegating work that stays inside the account and takes four or more dependent calls, would need `get_build_instructions`, or reads many entities to produce a small answer. Call tools directly for single reads, known-id edits, output that feeds your code, `submit_batch` and `run_simulation`, and anything that needs local files, secrets, keys, or client tokens. On a host that runs the call as an MCP task (Claude Code 2.1.304+, main conversation), the bar drops to three calls, the call returns at once, and the host delivers the digest; `wait_seconds` is ignored there. Elsewhere, leave `wait_seconds` unset unless you know your tool-call timeout: the server defaults to 240 on Claude Code and 45 elsewhere. Then follow the result's `next_step`. A result with `status: input_required` carries a `question`; answer it with `delegate_to_runtype { task_id, task: }`. + ## Platform docs | Tool | Use | @@ -349,16 +363,6 @@ Bring-your-own provider credentials: `list_provider_keys`, `create_provider_key` | `generate_proposal` | Scope-of-work proposal tool for a client project | | `generate-proposal` | MCP prompt variant of the proposal workflow | -## Delegation (flag-gated: `enableDelegateToRuntype`) - -| Tool | Use | -| --------------------- | ------------------------------------------------------------------------------------------------- | -| `delegate_to_runtype` | Hand a multi-step task to Runtype's in-account operator agent; streams progress, returns a digest | -| `check_delegation` | Long-poll a running delegation for events since `after` | -| `cancel_delegation` | Stop a running delegation; completed changes stay | - -When the account has the flag, the server instructions recommend delegating multi-step work (build or change a flow, agent, product, surface or tool; debug a run; load records; run evals). Pass `wait_seconds: 240` on Claude Code; keep it under 60 on clients with a 60-second tool timeout. A result with `status: input_required` carries a `question`; answer it with `delegate_to_runtype { task_id, task: }`. - Start with the `index` topic (task-to-topic map). Useful documentation topics include `platform-catalog`, `surface-types`, `flow-step-types`, `models`, `product-schema`, `types-fpo`, `types-flow-steps`, `types-entities`, `types-surface-configs`, `orthogonal-tools`, `builtin-tools`, `agent-skills`, `external-tools`, `external-agents`, `evals`, `limits`, `validation-errors`, `setup-readiness`, `dashboard-links`, `mock-ecommerce`, `persona-embed`, `persona-fullscreen-assistant`, and `sdk-reference`. For WebMCP page tools, read `persona-embed` and `types-surface-configs`. Configure diff --git a/skills/runtype/references/persona-widget.md b/skills/runtype/references/persona-widget.md index 951336f..af9844c 100644 --- a/skills/runtype/references/persona-widget.md +++ b/skills/runtype/references/persona-widget.md @@ -13,6 +13,7 @@ For current WebMCP and fullscreen layout details, prefer `persona-embed`, - [Client token](#client-token) - [Three integration options](#three-integration-options) - [Config reference](#config-reference) +- [V5 defaults and brand](#v5-defaults-and-brand) - [Programmatic access](#programmatic-access) - [WebMCP page tools](#webmcp-page-tools) - [Built-in client tools](#built-in-client-tools) @@ -29,8 +30,8 @@ These are the errors most agents make. Read this section first. - **Global script file**: `install.global.js`, NOT `index.umd.js`. - **API**: `initAgentWidget()`, NOT `Persona.mount()`, `window.Persona`, `window.RuntypePersona`. These don't exist. - **CSS**: When using ESM/manual setup, you **must** load `widget.css`. The script installer handles this automatically. -- **Ready event**: `persona:chat-ready`; `persona:ready` is only a deprecated alias. NOT `widget:ready` or `agentwidget:ready`. -- **Ready callback**: `onChatReady(handle)`; `onReady` is only a deprecated alias. +- **Ready event**: `persona:chat-ready`. NOT `persona:ready`, `widget:ready`, or `agentwidget:ready`. +- **Ready callback**: `onChatReady(handle)`. NOT `onReady`. - **Controller events**: use `user:message` and `assistant:complete`, NOT `message:sent` or `message:received`. ## CDN base URL @@ -43,9 +44,11 @@ https://cdn.runtype.com/persona/latest ``` Use `cdn.runtype.com` everywhere. It is the recommended source on every surface -(first-party, immutable, no third-party trust), and it is **required** on `publish_page` -preview pages: their strict Content Security Policy allows no other script source, so -third-party CDNs (jsdelivr, unpkg, esm.sh) are blocked there and fail silently. Deployed +(first-party, immutable, no third-party trust), and it is **required** on pages published +with `builtin:publish_page`, which you run through `execute_tool`. Their strict Content +Security Policy allows no other script source and blocks inline scripts, so third-party +CDNs (jsdelivr, unpkg, esm.sh) and inline init code fail silently. Use the script-installer +form with `data-*` attributes there. Deployed `static` apps allow scripts and styles from any https origin by default (an author can re-tighten via the manifest `csp` field), so third-party CDNs load on apps, but a remote script can change underneath an immutable deployed bundle, which is why the first-party @@ -64,21 +67,59 @@ A chat surface is optional: a token that names the agent in `agentIds` works on ## Current defaults to preserve -- Script-tag installs use the tiny `launcher.global.js` fast path for ordinary floating launchers and defer the full widget until first open when safe. -- Persona sanitizes rendered message HTML with DOMPurify by default. Keep `config.sanitize` enabled unless all rendered content is trusted. -- Shadow DOM is opt-in with `useShadowDom: true`; the default is `false` for CSS compatibility. -- For programmatic access, prefer `onChatReady` or `persona:chat-ready`. +These apply under V4 and V5 unless noted. Under `future.v5Defaults: true`, the look +changes as described in [V5 defaults and brand](#v5-defaults-and-brand), but the +behavior in this list stays the same. + +- Script-tag installs use the tiny `launcher.global.js` fast path for ordinary floating launchers and defer the full widget until first open when safe. With V5 defaults, the deferred launcher renders the same circle launcher as the full widget. +- Persona sanitizes rendered message HTML with DOMPurify by default. Keep `config.sanitize` enabled unless all rendered content is trusted. V5 does not change this. +- Shadow DOM is opt-in with `useShadowDom: true`; the default is `false` for CSS compatibility. V5 does not change this. +- For programmatic access, prefer `onChatReady` or `persona:chat-ready`. V5 does not change this. + +## V5 defaults and brand + +`future.v5Defaults: true` opts in to the V5 default styles. V4 stays the default until +you set the flag. The flag selects defaults only: explicit options and theme tokens always +win, and each affected setting stays independently configurable. + +With V5 defaults: + +- The launcher is a round button (`launcher.variant: "circle"`). Set `launcher.variant` to `"pill"` to keep the text-and-icon launcher. +- The composer is an overlay (`composer.placement: "overlay"`) with a fade over the transcript. +- Tool calls, reasoning, and approvals render as compact activity and decision rows. +- Artifacts are enabled, including the artifact pane. Set `features.artifacts.enabled` to `false` to turn off the pane, artifact cards, and inline previews. + +Use the top-level `brand` option to coordinate colors, typography, corners, density, and +elevation. Every field is optional, and it works with or without V5 defaults: + +- `accent`: Hex, `rgb()`, or `rgba()` with alpha 1. Drives accent colors, buttons, links, and focus. +- `neutral`: Same formats as `accent`. Drives backgrounds, surfaces, text, and borders. When `colorScheme` is omitted, a dark neutral selects dark mode. +- `font`: A CSS font-family string. Load custom fonts in the host page. +- `radius`: `none`, `sm`, `md`, or `lg` (0, 4, 8, or 16px). Circular controls stay circular. +- `density`: `compact`, `comfortable`, or `spacious`. Sets type size and header height. +- `elevation`: `flat`, `subtle`, or `raised`. Sets shadows and borders. + +```ts +config: { + future: { v5Defaults: true }, + brand: { accent: '#7c3aed', radius: 'lg', elevation: 'subtle' }, +} +``` + +Explicit `theme` and `darkTheme` values override `brand`. For example, an explicit +`theme.components.panel.borderRadius` wins over the brand's corners. ## Three integration options ### Option 1: Script installer (simplest) -One script tag, no CSS import needed. +One script tag, no CSS import needed. The `data-config` attribute turns on the V5 default styles. ```html ``` @@ -89,7 +130,7 @@ To mount in a specific container: ``` @@ -114,6 +155,7 @@ included, on `window.siteAgentConfig` and load the installer): config: { apiUrl: 'https://api.runtype.com', clientToken: 'YOUR_CLIENT_TOKEN', + future: { v5Defaults: true }, parserType: 'json', postprocessMessage: ({ text }) => markdownPostprocessor(text), launcher: { @@ -141,6 +183,7 @@ initAgentWidget({ target: '#chat', config: { ...DEFAULT_WIDGET_CONFIG, + future: { v5Defaults: true }, apiUrl: 'https://api.runtype.com', clientToken: 'YOUR_CLIENT_TOKEN', parserType: 'json', @@ -151,24 +194,27 @@ initAgentWidget({ ## Config reference -| Property | Type | Notes | -| ---------------------------------------- | ----------------------------- | ----------------------------------------------------------------- | -| `target` | string \| HTMLElement | CSS selector or DOM element | -| `useShadowDom` | boolean | Style isolation (default false) | -| `config.apiUrl` | string | `https://api.runtype.com` (or another configured Runtype API URL) | -| `config.clientToken` | string | Browser-safe client token from `create_client_token` | -| `config.parserType` | `'json'` | Always `'json'` for Runtype streams | -| `config.postprocessMessage` | function | Use `markdownPostprocessor` for rich text | -| `config.launcher` | object | `{ enabled, title, subtitle, position }` | -| `config.colorScheme` | `'light' \| 'dark' \| 'auto'` | Theme mode | -| `config.theme` | `DeepPartial` | Light theme overrides | -| `config.darkTheme` | `DeepPartial` | Dark theme overrides | -| `config.sanitize` | `boolean \| (html) => string` | Sanitize rendered message HTML; default uses DOMPurify | -| `config.webmcp` | object | Widget-side WebMCP page-tool discovery/execution config | -| `config.features.askUserQuestion.expose` | boolean | Advertise built-in LOCAL `ask_user_question` via `clientTools[]` | -| `config.features.suggestReplies.expose` | boolean | Advertise built-in LOCAL `suggest_replies` via `clientTools[]` | -| `windowKey` | string | Stores handle on `window[windowKey]` for programmatic access | -| `onChatReady` | `(handle) => void` | Callback when the controller API is callable | +| Property | Type | Notes | +| ---------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `target` | string \| HTMLElement | CSS selector or DOM element | +| `useShadowDom` | boolean | Style isolation (default false) | +| `config.apiUrl` | string | `https://api.runtype.com` (or another configured Runtype API URL) | +| `config.clientToken` | string | Browser-safe client token from `create_client_token` | +| `config.parserType` | `'json'` | Always `'json'` for Runtype streams | +| `config.postprocessMessage` | function | Use `markdownPostprocessor` for rich text | +| `config.launcher` | object | `{ enabled, title, subtitle, position }` | +| `config.colorScheme` | `'light' \| 'dark' \| 'auto'` | Theme mode | +| `config.future.v5Defaults` | boolean | Selects the V5 default styles; explicit options and theme tokens still win (default false) | +| `config.brand` | object | Coordinated `accent`, `neutral`, `font`, `radius`, `density`, `elevation`; see [V5 defaults and brand](#v5-defaults-and-brand) | +| `config.theme` | `DeepPartial` | Light theme overrides | +| `config.darkTheme` | `DeepPartial` | Dark theme overrides | +| `config.sanitize` | `boolean \| (html) => string` | Sanitize rendered message HTML; default uses DOMPurify | +| `config.webmcp` | object | Widget-side WebMCP page-tool discovery/execution config | +| `config.features.askUserQuestion.expose` | boolean | Advertise built-in LOCAL `ask_user_question` via `clientTools[]` | +| `config.suggestions.followUps.expose` | boolean | Advertise built-in LOCAL `suggest_replies` via `clientTools[]` | +| `windowKey` | string | Stores handle on `window[windowKey]` for programmatic access | +| `onChatReady` | `(handle) => void` | Callback when the controller API is callable; on a deferred install, it fires after the first open | +| `onLauncherShown` | `(info) => void` | Callback at page load for a floating launcher, with `{ deferred, element }` and no handle | ## Programmatic access @@ -180,7 +226,7 @@ Three ways. Pick by context. ``` @@ -190,6 +236,7 @@ Three ways. Pick by context. ``` -`onReady` and `persona:ready` still work as deprecated aliases, but do not use -them in new snippets. +On a deferred install, `persona:chat-ready` and `onChatReady` fire after the visitor first +opens the chat, so do not use them to open the chat at page load. To run code at page +load, use `onLauncherShown`. It applies to the floating launcher only and gives +`{ deferred, element }`, not a handle. ## WebMCP page tools +For tool design, native TypeScript authoring, and scenario verification, read +[Design and verify WebMCP page tools](https://github.com/runtypelabs/skills/blob/main/skills/runtype-persona/references/webmcp-authoring.md). Keep the deployment +and security configuration below when applying upstream WebMCP guidance. + WebMCP page tools are browser-side local tools registered on the embedding page with `document.modelContext.registerTool(...)`. Persona snapshots them at the start of each chat turn, sends them to Runtype as `clientTools[]` with @@ -236,8 +289,9 @@ tools first. Required setup: -1. Create a client token with `allowedOrigins` containing the exact embedding - page origin. +1. Create a client token with `product_surface_id` set to the chat surface and + `allowedOrigins` containing the exact embedding page origin. The binding is + fixed at creation, and an unbound token drops every page tool. 2. Enable page-tool consumption in the widget config: `webmcp: { enabled: true }`. 3. Set the chat surface `behavior.webmcp.enabled` to `true`. 4. Add origin-scoped allow-list rules when the surface should restrict which @@ -249,6 +303,7 @@ initAgentWidget({ target: '#chat', config: { clientToken: 'YOUR_CLIENT_TOKEN', + future: { v5Defaults: true }, webmcp: { enabled: true }, }, }) @@ -274,12 +329,19 @@ Rules: - Tool names are registered bare by the page. Runtype applies the `webmcp:` prefix after validation. +- Client-token chat skips a page tool whose name does not match + `^[a-zA-Z][a-zA-Z0-9_-]{0,63}$`. WebMCP allows longer names and dots. - Allow-list patterns match bare tool names. Use exact names, `*`, or one trailing wildcard such as `search_*`. - The HTTP `Origin` header is canonical. `pageOrigin` is diagnostic only. -- `requireConfirmFor` forces Persona's confirmation and is not a security - boundary. Chat dispatch does not enforce it; the voice direct route never - picks a listed tool. +- `requireConfirmFor` lists tools that always confirm. Persona reads the surface + list from `/v1/client/init` and merges it with the widget's + `webmcp.requireConfirmFor`. A matching tool skips `autoApprove`, still confirms + on a read-only voice call, and reaches a custom `onConfirm` with + `info.confirmRequired: true`. Proxy and direct-dispatch setups use only the + widget list. It is client-side confirmation, not a security boundary: chat + dispatch does not enforce it, and the voice direct route never picks a listed + tool. - The dashboard WebMCP tab shows discovered tools and observed origins from the trailing 7 days and can promote tools into allow-list rules. It shows an "Allow all tools" mode for the empty-allowlist case and reveals the rule @@ -314,10 +376,13 @@ these when the assistant needs common client-side UI primitives: ```ts config: { + future: { v5Defaults: true }, features: { askUserQuestion: { expose: true }, - suggestReplies: { expose: true }, - } + }, + suggestions: { + followUps: { expose: true }, + }, } ``` @@ -354,6 +419,7 @@ Three control layers: **visibility**, **behavior**, **styling**. ```ts config: { + future: { v5Defaults: true }, features: { showToolCalls: true, showReasoning: true, @@ -425,13 +491,14 @@ Reasoning bubbles do **not** have an imperative override layer. Style them via t Hidden internals (consumer-facing): ```ts -config: { features: { showToolCalls: false, showReasoning: false } } +config: { future: { v5Defaults: true }, features: { showToolCalls: false, showReasoning: false } } ``` Visible but not expandable: ```ts config: { + future: { v5Defaults: true }, features: { toolCallDisplay: { expandable: false }, reasoningDisplay: { expandable: false } @@ -459,14 +526,30 @@ theme: { For ChatGPT/Claude-style fullscreen split-pane layouts (chat on left, artifacts on right), read the `runtype://guide/persona-fullscreen-assistant` MCP resource. It covers the non-default `launcher.fullHeight`, panel-chrome removal, split artifact pane, document toolbar preset, custom composer plugin, and the dark palette those UIs use. +For an inline assistant that fills a host element instead of a fullscreen shell, use a frameless embed rather than `launcher.fullHeight`. Set `launcher: { enabled: false }` and `layout: { embedded: true }`. The host element needs a definite height, and the header stays hidden unless you set `layout.showHeader: true`. This works with V4 or V5 defaults. + +```ts +initAgentWidget({ + target: '#assistant', + config: { + apiUrl: 'https://api.runtype.com', + clientToken: 'YOUR_CLIENT_TOKEN', + future: { v5Defaults: true }, + launcher: { enabled: false }, + layout: { embedded: true }, + }, +}) +``` + ## Generating artifacts that embed the widget When generating standalone HTML files or Claude artifacts that embed the widget: 1. Use the **script installer** approach for simplicity. -2. For more control, use **ESM** and include `widget.css`. +2. For more control, load `index.global.js` in the browser or use the npm package in a bundled app, and include `widget.css`. 3. `clientToken` / `data-runtype-token` is the browser-safe client token from `create_client_token`. 4. API URL is `https://api.runtype.com` (or environment-appropriate). -5. Don't invent APIs. The only init function is `initAgentWidget()`. The current ready event is `persona:chat-ready` (`persona:ready` is deprecated). +5. Don't invent APIs. The only init function is `initAgentWidget()`. The ready event is `persona:chat-ready`. 6. For custom themes, call `get_persona_theme_reference` first; set explicit high-contrast component tokens. 7. For programmatic access, use `windowKey` + `onChatReady` or the `persona:chat-ready` listener. +8. Add `future: { v5Defaults: true }` to the widget config so the widget uses the V5 default styles. Under V5, the artifact pane is on by default; set `features.artifacts.enabled` to `false` to turn it off. diff --git a/skills/runtype/references/primitives.md b/skills/runtype/references/primitives.md index 12f8979..9c3d02e 100644 --- a/skills/runtype/references/primitives.md +++ b/skills/runtype/references/primitives.md @@ -70,7 +70,7 @@ When an agent isn't doing what you want, the first reach is to improve the syste Two different knobs that get confused. -- **`maxToolCalls`**: how many tool calls the agent can make in one execution. Default is 10. Raise it deliberately when the task requires several lookups, writes, or sub-agent calls in one turn. +- **`maxToolCalls`**: how many tool calls the agent can make in one turn. Default is 10. Raise it deliberately when the task requires several lookups, writes, or sub-agent calls in one turn. - **`agentLoop`** (`loopConfig.maxTurns`): a cap on how many _full turns_ the agent may take, each re-running with the previous results as context. The loop ends as soon as the model finishes its turn; it takes another turn only when the turn was cut off by the `maxToolCalls` budget, when the model call failed and is retried, or when a skill load or tool search expanded the tool surface (newly granted tools activate on the next turn, so skill-using agents need `maxTurns` of at least 2). It is a safety cap, not a target. A higher cap costs nothing on turns the agent never takes. The risk lives inside the loop, not in the ceiling: looping on the same goal repeats the same work unless you explicitly tell the agent to reflect or vary approach. Tune `maxToolCalls` before reaching for `agentLoop`. Raise `maxTurns` when the agent genuinely needs another pass: reflection, more tool calls than one turn's budget allows, or skill capabilities that only activate on a following turn. @@ -221,19 +221,18 @@ When you bind capabilities to a `mcp` or `api` surface, the platform **automatic You're not coding API endpoints; you're declaring which capabilities go on which surface. -### The orchestrator (when multiple capabilities → one conversational surface) +### Capability routing (when multiple capabilities → one surface) -When **more than one capability** is connected to a conversational surface (`chat`, `slack`, `telegram`, `discord`, `email`, etc.), Runtype **automatically provisions an orchestrator agent**. It decides which capability handles each incoming message. +On a `chat` surface, `behavior.mode` decides which capability handles a message: -Defaults: +- `single_orchestrator` (default): every message goes to the enabled entry point, then `orchestratorCapabilityId`, then the first capability. +- `multi_capability`: a router picks a capability for each message. -- Inexpensive fast model (because routing at 10-20s defeats the purpose). -- Minimum data over the wire, usually just a short label per capability. -- Alphabetical labels (A, B, C…) for the route options. +The router makes one call at temperature 0 with `gpt-5.4-nano` by default. It lists capabilities by number and reads back a number. Set `behavior.router` (`model`, `prompt`) and `behavior.fallbackCapabilityId` to override this. It runs on product chat (`POST /v1/products/{productId}/surfaces/{surfaceId}/chat`) and in surface evals. Client-token chat runs the token's target and does not route. **Run a surface eval (dashboard)** to compare routing strategies before launch. -Overridable: model, system prompt, routing logic. **Run a surface eval (dashboard) on the orchestrator** to compare routing strategies before launch. +Messaging channels have no modes. See `surfaces.md` for their rule. -Practical implication: you don't need to write your own "router agent." Add the capabilities, let the orchestrator route. +Practical implication: you don't need to write your own "router agent." Add the capabilities and set the mode. ## Surface @@ -272,7 +271,7 @@ Filtering supports complex queries: `recordFilter: { type, where }` with conditi Cron or one-time trigger. -Shape: `target` (exactly one of `flow_id` or `agent_id`; flow schedules may add `record_ids` or `record_type`), `trigger` (`{ type: "recurring", cron, timezone }` or `{ type: "one_time", run_at }`), and `messages` passed to each run. +Shape: `target` (exactly one of `flow_id` or `agent_id`; flow schedules may add `record_ids` or `record_type`), `trigger` (`{ type: "recurring", cron, timezone }` or `{ type: "one_time", run_at }`), `inputs` (variables for each flow run), and `messages` passed to each run. Agents store `inputs` but do not apply them, so use `messages` for an agent. For flows: standard "call function on schedule." For agents: the trigger looks like a message being pushed into a conversation, which is useful for **heartbeat patterns** ("every morning, check the todo list and decide what to do"). Schedules can also fan out as a batch over all records of a particular type. diff --git a/skills/runtype/references/recipes.md b/skills/runtype/references/recipes.md index c4db406..ae9c3bc 100644 --- a/skills/runtype/references/recipes.md +++ b/skills/runtype/references/recipes.md @@ -14,7 +14,7 @@ These are sketches, not copy-paste configs. The exact JSON shapes are best disco - [Recipe 6: Eval harness for an agent change](#recipe-6-eval-harness-for-an-agent-change) - [Recipe 7: Multi-agent system](#recipe-7-multi-agent-system) - [When to package as an FPO template](#when-to-package-as-an-fpo-template) -- [Recipe 8: Multi-capability product with auto-orchestrator](#recipe-8-multi-capability-product-with-auto-orchestrator) +- [Recipe 8: Multi-capability product with capability routing](#recipe-8-multi-capability-product-with-capability-routing) - [Recipe 9: Federate an external CrewAI agent into a Runtype product](#recipe-9-federate-an-external-crewai-agent-into-a-runtype-product) - [Recipe 10: Browser-side page tools for an embedded assistant (WebMCP)](#recipe-10-browser-side-page-tools-for-an-embedded-assistant-webmcp) - [Recipe 11: Privacy-sensitive product with hidden parameters + server-side local tools](#recipe-11-privacy-sensitive-product-with-hidden-parameters--server-side-local-tools) @@ -102,7 +102,7 @@ These are sketches, not copy-paste configs. The exact JSON shapes are best disco 3. **Schedule**: `create_schedule`: - `target: { flow_id }` - `trigger: { type: "recurring", cron: "0 8 * * 1-5", timezone: "America/New_York" }` - - `messages`: any per-run input (e.g. recipient list); fire-time variables such as `{{_now.date}}` resolve in the schedule's timezone + - `inputs`: variables each run receives (e.g. recipient list), referenced as `{{varName}}`; fire-time variables such as `{{_now.date}}` resolve in the schedule's timezone 4. **Test**: `run_schedule_now` for an immediate manual run. Check `list_schedule_runs` for status, `trace_execution` for any failures. **Gotchas:** @@ -145,16 +145,16 @@ These are sketches, not copy-paste configs. The exact JSON shapes are best disco 1. **Agent**: `create_agent` with the support persona and any tools it needs (FAQ search, ticket creation, etc.). 2. **Product** + capability binding. 3. **Surface**: `create_surface` of type `chat`. Configure the launcher, theme, and visible features (`showToolCalls`, `showReasoning`). If the widget must call browser-side page tools, configure `behavior.webmcp` with an origin-scoped allowlist. -4. **Client token**: `create_client_token` creates a public, scoped, revocable token that the browser-side widget uses. -5. **Embed code**: `generate_persona_embed_code` returns a ready-to-paste HTML snippet. **Prefer this over hand-writing the embed.** -6. **Page tools (optional)**: If using WebMCP, set widget `config.webmcp.enabled`, then register tools on `document.modelContext` before Persona initializes. Keep the client token's `allowedOrigins` aligned with the `behavior.webmcp` origins. -7. **Theming**: Before generating a custom theme, call `get_persona_theme_reference` to load the design-token docs and example themes. See `persona-widget.md` for the contrast rules and theming gotchas. Header tokens are easy to get wrong. +4. **Client token**: `create_client_token` creates a public, scoped, revocable token that the browser-side widget uses. For page tools, set `product_surface_id` to the chat surface. This value is fixed at creation, and an unbound token drops every page tool. +5. **Embed code**: `generate_persona_embed_code` returns a ready-to-paste HTML snippet. **Prefer this over hand-writing the embed.** Then add `future: { v5Defaults: true }` to its config so the widget uses the V5 default styles. +6. **Page tools (optional)**: If using WebMCP, set widget `config.webmcp.enabled`, then install `@mcp-b/webmcp-polyfill` and register tools on `document.modelContext`. Persona's own fallback arrives too late for registration at page load. See Recipe 10. Keep the client token's `allowedOrigins` aligned with the `behavior.webmcp` origins. +7. **Theming**: Before generating a custom theme, call `get_persona_theme_reference` to load the design-token docs and example themes. See `persona-widget.md` for the contrast rules and theming gotchas. Header tokens are easy to get wrong. For a coordinated look, use the top-level `brand` option before you write component tokens. Under V5 defaults, the artifact pane is on; set `features.artifacts.enabled` to `false` to turn it off. **Gotchas:** - Wrong package name (`@runtype/persona` vs `@runtypelabs/persona`; the latter is correct), wrong API (`Persona.mount()` doesn't exist; use `initAgentWidget()`), wrong CSS path are common errors. The MCP-generated embed code avoids all of these. - For consumer-facing widgets, set `features.showToolCalls: false` and `features.showReasoning: false`. For internal debug surfaces, leave them on. -- To let the model ask structured follow-up questions or propose reply chips, expose Persona's built-in LOCAL tools with `features.askUserQuestion.expose` and `features.suggestReplies.expose` instead of inventing custom tool UIs. +- To let the model ask structured follow-up questions or propose reply chips, expose Persona's built-in LOCAL tools with `features.askUserQuestion.expose` and `suggestions.followUps.expose` instead of inventing custom tool UIs. - Do not model browser-side page actions as an `mcp` surface. Use WebMCP on the `chat` surface when the capability must run inside the user's page. --- @@ -187,15 +187,15 @@ For a one-time model or prompt comparison, `submit_eval` with several eval confi Three viable patterns. Pick by where the routing decision lives. -**Pattern A: Auto-orchestrator (Runtype-managed)**: preferred when each sub-agent is independently useful +**Pattern A: Capability routing (Runtype-managed)**: preferred when each sub-agent is independently useful - Build each sub-agent independently. Each is its own agent with its own tools. - Add all sub-agents as capabilities of the product. -- Bind all of them to the same conversational surface. -- **Runtype auto-provisions an orchestrator agent** that routes incoming messages to the right sub-agent. -- See Recipe 8 for the orchestrator-eval workflow. +- Bind all of them to the same `chat` surface. +- Set `behavior.mode: "multi_capability"` on the surface. The default mode sends every message to one capability. +- See Recipe 8 for the setup and eval workflow. -This is the default choice for multi-agent products. The platform handles the routing. +This is the default choice for multi-agent products. The platform runs the routing. **Pattern B: Sub-agents as tools**: preferred when one agent should be primary and others assist @@ -213,7 +213,7 @@ Choose A if multiple capabilities should be exposed to users via the same surfac **Gotchas:** -- Pattern A: routing should be fast. If the orchestrator is slow, override to a smaller model or tune the system prompt. +- Pattern A: routing should be fast. If the router is slow, set a smaller `behavior.router.model`. - Pattern B risks unbounded loops. Cap with `maxToolCalls`. Sub-agents should not call back into the orchestrator (no recursion). - Pattern C: less flexible but most predictable. Cost-effective for known workflows. @@ -231,7 +231,7 @@ The result is a single distributable JSON document someone else can import in on --- -## Recipe 8: Multi-capability product with auto-orchestrator +## Recipe 8: Multi-capability product with capability routing **Shape**: A web chat that exposes three agents (sales, support, billing) and routes user messages automatically. @@ -242,13 +242,33 @@ The result is a single distributable JSON document someone else can import in on 3. `add_product_capability` three times, once per agent. 4. `create_surface` of type `chat`. 5. `add_surface_item` three times, wiring each capability into the same surface. -6. **Runtype auto-provisions an orchestrator** because multiple capabilities are bound to the same conversational surface. -7. Test the routing: send messages that obviously belong to each capability and verify they reach the right agent. `trace_conversation` shows the orchestrator's routing decisions. -8. **Run a surface eval (dashboard) on the orchestrator** before launch. Send a set of messages with expected routing through the surface and compare strategies. +6. Turn on routing with `update_surface`. The default mode, `single_orchestrator`, sends every message to one capability. `behavior` is merged shallowly, and the surface needs at least one enabled capability: + ```json + { + "behavior": { + "mode": "multi_capability", + "router": { "model": "gpt-5.4-nano" }, + "fallbackCapabilityId": "" + } + } + ``` +7. Test the routing: send messages that obviously belong to each capability to `POST /v1/products/{productId}/surfaces/{surfaceId}/chat` and verify they reach the right agent. `trace_conversation` shows the routing decisions. +8. **Run a surface eval (dashboard) on the routing** before launch. Send a set of messages with expected routing through the surface and compare strategies. + +Routing runs on that product chat route and in surface evals. A Persona widget on a client token (`/v1/client/chat`) does not route: it runs the token's target. + +**When to override the router default**: only if routing is slow (>1s) or wrong. The router makes one call at temperature 0, and the default model is `gpt-5.4-nano`. It lists each capability as `[n] name: description`, so improve the capability descriptions first. If routing is still borderline, set `behavior.router.prompt`. Keep `{{capabilities}}`, `{{fallback}}`, and `{{message}}`, because Runtype adds nothing else to the prompt, and ask for the number: -**When to override the orchestrator default**: only if routing is slow (>1s) or wrong. The default uses an inexpensive model with minimum data over the wire. Customize the orchestrator's system prompt with domain hints if routing is borderline: +> "Route the user message to a capability. Sales covers pricing, demos, and plans. Support covers broken features and how-to questions. Billing covers invoices and refunds. +> +> Capabilities: +> {{capabilities}} +> +> Respond with only the capability number. If none fits, respond with {{fallback}}. +> +> User message: {{message}}" -> "Sales-related questions (pricing, demos, plans): route to A. Support questions (broken features, how-to): route to B. Billing questions (invoices, refunds): route to C. When ambiguous, prefer B." +Runtype reads the number from the reply (`3`, `[3]`, `3.`, or `option 3`). If it finds no number, it tries a capability name, then uses the fallback. --- @@ -280,25 +300,48 @@ The result is a single distributable JSON document someone else can import in on **Steps**: 1. Build the agent and a `chat` surface as in Recipe 5. Set the surface `behavior.webmcp.enabled: true` and add origin-scoped `behavior.webmcp.allowlist` rules, e.g. `{ origin: "https://app.example.com", tools: ["read_page", "open_record"] }`. -2. Create a client token whose `allowedOrigins` includes the app origin, and generate the embed with `generate_persona_embed_code`. +2. Create a client token with `product_surface_id` set to the chat surface and `allowedOrigins` including the app origin, then generate the embed with `generate_persona_embed_code`. The binding is fixed at creation, and an unbound token drops every page tool. 3. In the widget config set `webmcp: { enabled: true }`. -4. In the page, register tools on `document.modelContext` (Persona reads the registry at the start of each turn): +4. In the page, install the polyfill and register tools on `document.modelContext`. `document.modelContext` is undefined on a browser without native support until something installs it, and Persona's fallback arrives only at the first dispatch. Persona reads the registry at the start of each turn. In this sample, `canOpenRecord` and `openRecord` are your app's functions: ```ts - document.modelContext.registerTool({ - name: 'open_record', - description: 'Open the record detail view for a given record id', - inputSchema: { - type: 'object', - properties: { recordId: { type: 'string' } }, - required: ['recordId'], - }, - async execute({ recordId }) { - router.push(`/records/${recordId}`) - return { opened: recordId } - }, - }) + import { installWebMCP } from '@mcp-b/webmcp-polyfill' + + installWebMCP() // keeps native support + const registration = new AbortController() // abort on unmount + const context = document.modelContext + + if (context) { + await context.registerTool( + { + name: 'open_record', + description: 'Open the detail view for a record id. Use after the user picks a record.', + inputSchema: { + type: 'object', + properties: { recordId: { type: 'string' } }, + required: ['recordId'], + }, + annotations: { readOnlyHint: false, consequentialHint: false }, + async execute({ recordId }, options) { + if (typeof recordId !== 'string' || !canOpenRecord(recordId)) { + return { + isError: true, + content: [ + { + type: 'text', + text: 'That record is unavailable. Ask the user to pick another.', + }, + ], + } + } + await openRecord(recordId, { signal: options?.signal }) + return { content: [{ type: 'text', text: `Opened record ${recordId}.` }] } + }, + }, + { signal: registration.signal } + ) + } ``` -5. Persona sends the registered tools with each turn, runs the model's calls in the page, and returns the results through Runtype. It shows an approval bubble per call unless `webmcp.autoApprove` allows it; reserve auto-approval for safe reads. +5. Persona sends the registered tools with each turn, runs the model's calls in the page, and returns the results through Runtype. It shows an approval bubble per call unless `webmcp.autoApprove` allows it; reserve auto-approval for safe reads, and list consequential tools in the surface's `behavior.webmcp.requireConfirmFor` so they always confirm. **Why this matters**: the LLM gets real agency over the front-end without a server-side bridge for every operation. For tools that must run on your server instead, use SDK local tools (`runWithLocalTools` in `@runtypelabs/sdk`). See `persona-widget.md` for the full WebMCP setup. diff --git a/skills/runtype/references/surfaces.md b/skills/runtype/references/surfaces.md index 634f78d..e46a509 100644 --- a/skills/runtype/references/surfaces.md +++ b/skills/runtype/references/surfaces.md @@ -11,7 +11,7 @@ Many surfaces carry an `executionHint` that should be appended to the agent's sy - [Trait dimensions](#trait-dimensions) - [Surface type catalog](#surface-type-catalog) - [Auto-generated REST and MCP APIs](#auto-generated-rest-and-mcp-apis) -- [The orchestrator (multi-capability conversational surfaces)](#the-orchestrator-multi-capability-conversational-surfaces) +- [Capability routing (multi-capability surfaces)](#capability-routing-multi-capability-surfaces) - [Surface-specific auto-registered tools](#surface-specific-auto-registered-tools) - [Picking a surface](#picking-a-surface) - [Trait-driven prompt construction](#trait-driven-prompt-construction) @@ -28,7 +28,7 @@ Many surfaces carry an `executionHint` that should be appended to the agent's sy | `inboundMediaSupport` | Whether the channel accepts inbound media (images, files) | | `consumerType` | `human` / `machine` / `agent`: informs the eval framing | | `reasoningVisibility` | `pass_through` / `always_strip`: whether `` traces are exposed | -| `markdownDialect` | `none` / `markdown` / `mdx` / `mrkdwn` / `html` | +| `markdownDialect` | `none` / `markdown` / `mdx` / `mrkdwn` / `markdownv2` / `html` / `telegram_html` | | `threadModel` | `flat` / `threaded` / `reply_chain` | | `senderIdentity` | `anonymous` / `authenticated` / `verified` | | `maxResponseLength` | Response length budget/cap (chars) | @@ -78,7 +78,7 @@ Code Mode MCP server for programmatic agent access, for advanced agent integrati Email-triggered processing and automated responses. - Use cases: auto-reply support agent, invoice processor, email-to-task converter -- `deliveryModel: async`, `mediaSupport: rich`, `markdownDialect: html` +- `deliveryModel: async`, `mediaSupport: images`, `markdownDialect: html` - `reasoningVisibility: always_strip`: never leak thinking traces - `threadModel: reply_chain` - **Execution hint**: "Respond via email. Write in a professional, organized tone. Use clear paragraphs. Avoid bullet-point overload; prefer flowing prose where appropriate. Don't include reasoning traces, tool call narration, or internal process details." @@ -153,18 +153,13 @@ WhatsApp Business for customer communication. Telegram bot for messaging. - Use cases: support, notifications, group admin -- `mediaSupport: rich`, `interactiveUI: buttons`, `markdownDialect: html`, `maxResponseLength: 4096` +- `mediaSupport: rich`, `interactiveUI: buttons`, `markdownDialect: telegram_html`, `maxResponseLength: 4096` - `messagesMutable: true`, `threadModel: flat` - **Execution hint**: clear and concise, no unnecessary verbosity, no reasoning traces -### `messaging` +### Retired: `messaging` -Generic messaging surface for multi-channel delivery. - -- Use cases: unified support, channel-agnostic bots, internal routing across messaging providers -- `deliveryModel: real_time`, `mediaSupport: images`, `markdownDialect: none` -- Use when live docs expose a generic messaging integration for the target workflow. Prefer dedicated surfaces (`sms`, `whatsapp`, `telegram`, etc.) when channel-specific constraints, formatting, identity, or setup matter. -- **Execution hint**: clear, concise, plain-text-safe responses with no reasoning traces +The generic `messaging` type is retired, and no route serves it. An FPO that names it still parses, with a warning. Use one surface per channel (`sms`, `whatsapp`, `telegram`, and so on). ### `a2a` @@ -181,6 +176,25 @@ Hosted publisher page for exposing one or more capabilities as a branded mini-ap - Use cases: public mini-apps, customer-facing tools, authenticated internal pages - Presentation config lives on surface items; product-level page behavior controls route, auth requirement, nav style, branding, and social metadata - Read `runtype://types/surface-configs` before authoring because this surface has structured `HostedPageBehavior` and `HostedPagePresentation` fields +- Hidden from the dashboard and from MCP `create_surface` + +### `chrome_extension` + +Downloadable Manifest V3 Chrome extension that embeds the agent in the browser side panel. + +- Use cases: browser copilots, page-aware assistants, form filling and data extraction, internal browser tooling +- Streaming is required. `mediaSupport: images`, `interactiveUI: generative`, `markdownDialect: mdx` +- Caller credential: client token + +### `ag-ui` + +AG-UI protocol endpoint for custom agent front ends, such as CopilotKit clients. + +- Hidden from the catalog and flag-gated, and MCP `create_surface` does not accept it +- Streaming is required. `deliveryModel: real_time`, `mediaSupport: none` +- Caller credential: client token + +MCP `create_surface` also does not accept `imessage`. ## Auto-generated REST and MCP APIs @@ -193,19 +207,25 @@ When you bind capabilities to a `mcp` or `api` surface, the platform **auto-gene So mapping three agents to one `mcp` surface gives you three MCP tools on one server. Mapping the same three agents to one `api` surface gives three REST endpoints. -## The orchestrator (multi-capability conversational surfaces) +## Capability routing (multi-capability surfaces) + +**On `chat`**, `behavior.mode` decides which capability handles a message: + +- `single_orchestrator` (default): every message goes to the enabled entry point, then `orchestratorCapabilityId`, then the first capability. +- `multi_capability`: a router picks a capability for each message. An active chat surface still needs exactly one enabled entry point. -When more than one capability is bound to a single **conversational** surface (`chat`, `slack`, `telegram`, `discord`, `email`, `whatsapp`, etc.), Runtype provisions an **orchestrator agent** automatically. It decides which capability handles each incoming message. +The router makes one call at temperature 0, with `gpt-5.4-nano` by default. It lists capabilities as `[n] name: description` and reads a number from the reply, then tries a capability name, then uses the fallback. The fallback is `behavior.fallbackCapabilityId` if that capability can be routed to, or the first capability. -Defaults are designed for fast, cheap routing: +Set `behavior.router.model` and `behavior.router.prompt` to override it. A custom prompt must keep `{{capabilities}}`, `{{fallback}}`, and `{{message}}`. Routing runs on product chat (`POST /v1/products/{productId}/surfaces/{surfaceId}/chat`) and in surface evals. Client-token chat (`/v1/client/chat`) runs the token's target and does not route. **Run a surface eval (dashboard)** to compare strategies: default vs. tuned prompt, small model vs. larger. -- Small inexpensive model -- Minimum data over the wire -- Alphabetical-label voting (A/B/C…) +**On messaging channels** (`slack`, `telegram`, `discord`, `email`, `whatsapp`, and others), modes do not apply. Runtype applies these rules in order: -Overridable: model, system prompt, label scheme. **Run a surface eval (dashboard) on the orchestrator** to compare strategies: out-of-box vs. tuned, alphabetical vs. semantic, small model vs. larger. +1. An enabled entry point handles the message. +2. If at most one capability is enabled, it handles the message. +3. A platform judgment picks among up to 20 capabilities. +4. With more than 20, the first routable capability handles the message. -If you need a custom router, you can replace the default, but try the default first. Routing should usually be a sub-second operation. +Routing should usually be a sub-second operation. ## Surface-specific auto-registered tools @@ -229,10 +249,10 @@ You don't manually add these. The agent adapts. > "I want to run something every morning at 9" → `schedule` > "I need an email auto-responder" → `email` > "I have one bot that should work over SMS, WhatsApp, and Telegram" → three surfaces (one per channel) with channel-specific tuning. The channels' constraints diverge enough that per-surface configuration almost always beats a single shared surface. -> "I need a generic multi-channel messaging gateway" → `messaging` > "I want to federate an external agent into my product" → `create_agent` with `agent_type: "external"` (A2A or `runtype-stream` endpoint), then add it as a capability > "I want other agents to call my product over A2A" → `a2a` > "I want Runtype to host a branded mini-app for this product" → `hosted-page` +> "I want the agent in the Chrome side panel" → `chrome_extension` ## Trait-driven prompt construction diff --git a/skills/tool-design-composition/SKILL.md b/skills/tool-design-composition/SKILL.md index 814ad73..97bfd0b 100644 --- a/skills/tool-design-composition/SKILL.md +++ b/skills/tool-design-composition/SKILL.md @@ -1,8 +1,6 @@ --- name: tool-design-composition description: 'Compose and expose agent toolsets: task-level operations, batching, discovery, dry runs, and versioning.' -user-invocable: true -argument-hint: '[tool set to organize or extend]' --- # Tool Composition and Discovery Design @@ -102,8 +100,10 @@ error the tool returns when the prerequisite is missing. ### Catalog the set when it is large (Tool Registry, Capability Matching) -Past roughly twenty tools, tool-selection accuracy drops and every definition costs -context tokens. +Every tool definition costs context tokens, and selection gets harder as the set grows. +Anthropic reports that selection accuracy degrades past 30 to 50 tools and recommends +tool search at 10 or more. OpenAI suggests fewer than 20 tools at a time and calls this a +soft suggestion. Twenty is Runtype's tool-search threshold, not a measured limit. Provide a `list_available_tools(category)` registry with name, description, category, and auth requirements, and a `find_tool_by_intent(intent)` search that ranks tools by semantic match with confidence and usage examples. Where your runtime can defer tools, @@ -136,7 +136,7 @@ Cache the status briefly. ## Anti-patterns -- Thirty atomic tools and no bundle for the sequence 80% of runs perform. +- Thirty atomic tools and no bundle for the sequence most runs perform. - `delete_files` with no preview mode. - Two tools that differ only in one optional parameter. - A registry that lists tools without their auth requirements or categories. @@ -149,14 +149,16 @@ Cache the status briefly. it caps the request's serialized `runtimeTools` at 1 MB. A model provider can still refuse a long tool list (`TOOL_COUNT_REFUSED_BY_PROVIDER`), so use tool search for large tool sets. Tool search is on by default for multi-turn agents: at 20 or more - tools, Runtype keeps a hot set loaded and defers the inline runtime tools behind a - `tool_search` tool that the model calls to load more. Saved, built-in, and MCP tools stay loaded. Set + capability tools (inline, saved, built-in, and MCP alike), Runtype keeps a hot set + loaded and defers the rest behind a `tool_search` tool that the model calls to load + more. Pin a tool with `tools.toolSearch.alwaysLoaded`. Set `tools.toolSearch.enabled: false` to send every tool on every request. Single-turn agents and flow prompt steps always send every tool, so keep those sets small or split them across subagents. Either way, make descriptions distinct, because they are what the model chooses by and what `tool_search` matches against. -- **Tool-call budget.** An agent makes at most 10 tool calls per execution unless you - set `config.tools.maxToolCalls`. A per-item loop over a list uses up that budget +- **Tool-call budget.** An agent makes at most 10 tool calls per turn unless you set + `config.tools.maxToolCalls` (1 to 100). A call past the cap gets the tool error + `Tool call limit of N reached`. A per-item loop over a list uses up that budget quickly, so ship a batch form, or raise the cap on purpose. - **Task bundle and tool chain.** A flow is the platform's explicit chain: fixed step order, data passing, per-step error handling. Expose it as one tool @@ -193,7 +195,8 @@ Cache the status briefly. deterministically with no approval gate, so there a preview must be a distinct tool or a `mode` parameter. Approval details: `get_platform_documentation(topic="agent-design")`. -- **Description length.** A new saved tool's description is capped at 500 characters. When +- **Description length.** A new saved tool's description is capped at 500 characters on + create and 5,000 on update. Keep it short anyway. When dependency hints, replacement notes, and deprecation notes do not fit, move them into parameter descriptions or the error text. - **Registry and discovery.** `list_tools` covers saved tools, diff --git a/skills/tool-design-errors/SKILL.md b/skills/tool-design-errors/SKILL.md index f3e45b2..f3b8ba3 100644 --- a/skills/tool-design-errors/SKILL.md +++ b/skills/tool-design-errors/SKILL.md @@ -1,8 +1,6 @@ --- name: tool-design-errors description: 'Design actionable agent tool errors, ambiguity handling, retry guidance, and fallback behavior, or debug an agent that loops on or misreads a failing tool.' -user-invocable: true -argument-hint: '[tool whose failure paths to design]' --- # Tool error design @@ -95,7 +93,7 @@ success. ### Thresholds decide when to ask (Fuzzy Match Threshold) Confirming every match is slow. Never confirming is dangerous. Pick thresholds and -document them. A reasonable starting point: +document them. These numbers are a heuristic starting point, not a measured standard: - Above 90% confidence: auto-accept, and log the match for audit. - 50% to 90%: return the candidates as a confirmation request. @@ -174,7 +172,7 @@ whether partial results are attached, and whether an async variant exists. See the body. A 2xx response that carries an error payload counts as a success and gets no `errorType`. - **To classify a third-party API you do not control**, wrap the call in a `flow` tool. - An `api-call` step with `errorHandling: "continue"` writes its `defaultValue` when + An `api-call` step with `errorHandling: { "onError": "continue" }` writes its `defaultValue` when the call fails, so set `defaultValue` to a structured error object, and add a `transform-data` step that gives success and failure one result shape. If the step has a `responseMapping`, the mapping also applies to `defaultValue`, so map the error @@ -182,10 +180,17 @@ whether partial results are attached, and whether an async variant exists. See one fixed class. A `custom` tool has no network egress unless it opts in with `networkAccess` (and `secrets` for credentials); then it can make the call and shape the failure class itself. -- **For an MCP server tool, put the class and recovery steps in the content text.** - Runtype passes the `content` of a `tools/call` result to the model and does not read - `isError`, so a result with `isError: true` is recorded as a successful call. A - non-2xx HTTP response or a JSON-RPC error is still reported as a failed call. +- **For an MCP server tool, return `isError: true` and put the class and recovery steps + in the content text.** On hosted Runtype lanes, a result with `isError: true` fails the + call, and the content text becomes the error the model reads. A non-2xx HTTP response + or a JSON-RPC error is also reported as a failed call. The self-hosted runtime + (`@runtypelabs/runtime`) still reads only `content` on its direct MCP path, so there + an `isError` result counts as a success. Keep the error text readable either way. +- **Map errors onto the transport's flag.** MCP marks a failed tool result with + `isError: true`, and Anthropic's API marks it with `is_error` on the `tool_result` + block. Report invalid arguments the same way, as a tool execution error the model + can read, not as a protocol error. The model can correct its call only from an error + it sees. - **`external` tool calls time out after 30 seconds**, and the model receives a `timeout` error. For slower upstreams, use a detached `subagent` tool (see `tool-design-execution`). @@ -210,7 +215,7 @@ the recovery step tell the user to reconnect the server from **Tools**. ### Confirmation requests on chat surfaces Behind a Persona widget, expose the built-in local tools -(`features.askUserQuestion.expose`, `features.suggestReplies.expose`). An ambiguous +(`features.askUserQuestion.expose`, `suggestions.followUps.expose`). An ambiguous match then becomes a rendered choice that the user taps, not a JSON options list that the model has to narrate. Elsewhere, return the options in the tool result as shown above. @@ -230,8 +235,9 @@ Some flow steps continue when they fail. This partial list shows the behavior wh - A `tool-call` step ignores `errorHandling`. It uses `config.onError`, which fails the step by default. With `onError: "continue"`, it writes `{ error, result: null }`. -Set `errorHandling` to `"fail"` or `"continue"` explicitly on any step where a silent -continue would hide a real failure from the agent. +Set `errorHandling` to `{ "onError": "fail" }` or `{ "onError": "continue" }` +explicitly on any step where a silent continue would hide a real failure from the agent. +A bare string fails validation. ### Pauses and retries diff --git a/skills/tool-design-execution/SKILL.md b/skills/tool-design-execution/SKILL.md index a87392a..5bcf33b 100644 --- a/skills/tool-design-execution/SKILL.md +++ b/skills/tool-design-execution/SKILL.md @@ -1,8 +1,6 @@ --- name: tool-design-execution description: 'Design how an agent tool runs: sync or async job, idempotency, timeouts, transactions, and compensation. Use when a tool is slow, has side effects that a retry could duplicate, or spans several systems.' -user-invocable: true -argument-hint: '[tool whose execution semantics to design]' --- # Tool Execution Design @@ -56,6 +54,11 @@ One tool starts the job and returns immediately. Sibling tools poll and fetch: - The start tool's description says the operation is long and names the polling tool, so the agent does not wait on the first call. +MCP also has an opt-in tasks extension (`io.modelcontextprotocol/tasks`) for this +pattern. The client polls with `tasks/get` and sends input with `tasks/update`. Use it +only when both the client and the server support it. Otherwise, use the job-handle tools +above. + ### Retries must be harmless (Idempotent Operation) Query tools are idempotent by nature. Command tools need one of: diff --git a/skills/tool-design-interface/SKILL.md b/skills/tool-design-interface/SKILL.md index d63d0f4..28be343 100644 --- a/skills/tool-design-interface/SKILL.md +++ b/skills/tool-design-interface/SKILL.md @@ -1,8 +1,6 @@ --- name: tool-design-interface description: 'Design agent-facing tool names, descriptions, and parameter schemas; diagnose incorrect tool selection or inputs.' -user-invocable: true -argument-hint: '[tool whose name, description, or parameters to design]' --- # Tool Interface Design @@ -40,6 +38,11 @@ cacheable, and parallelizable; say so (the MCP annotation `readOnlyHint: true`, "Safe to retry" in the description). Command tools modify state; document irreversibility in the first sentence ("Permanently deletes the user. Irreversible.") and flag them destructive where the runtime supports it (`destructiveHint: true`). + +Set all four MCP hints explicitly. Unset, they default to `readOnlyHint: false`, +`destructiveHint: true`, `idempotentHint: false`, and `openWorldHint: true`. A client +treats hints as untrusted unless the server is trusted, so they never replace a +permission check. Discovery tools (`list_tables`, `get_capabilities`, `who_am_i`) exist so the agent can find out what is possible before acting; their descriptions say "call this first". @@ -89,9 +92,22 @@ Free-form strings invite invalid values and waste tokens on error handling. } ``` -Enums are self-documenting; still list the values in the description. Never assume -the model obeys the schema: it can hallucinate an unsupported enum value or an -out-of-range number. Validate early and fail with an error that lists the valid values. +Enums are self-documenting; still list the values in the description. Without strict +tool use, never assume the model obeys the schema: it can send an unsupported enum +value or an out-of-range number. Validate early and fail with an error that lists the +valid values. + +Strict tool use (`strict: true`) makes the provider sample only schema-valid inputs. It +narrows what the schema can say: + +- Anthropic rejects `minimum`, `maximum`, `minLength`, and `maxLength` with a 400, and + accepts only a fixed list of string formats. Objects must set + `additionalProperties: false`. +- OpenAI requires `additionalProperties: false` and lists every field in `required`. + +For a strict tool, move the range or length rule into the description and enforce it in +code. Runtype does not send `strict` to providers, so validate inputs in the tool on +Runtype. ### Fewer required parameters @@ -120,7 +136,7 @@ When a tool takes alternative selectors, the description lists every valid combi ("Provide exactly one of `conversationId`, `channelName`, or `userEmails`"), the tool counts what was supplied at the start of execution, and a violation returns a clear error naming the valid options. Express the rule in the schema too where the runtime -supports `oneOf`. +supports `oneOf`. Check the provider's schema limits first. ### Say what is faster or cheaper @@ -145,6 +161,10 @@ variation; it never widens a constrained enum or bypasses validation. - Verb-object names; the same verb means the same thing across the set (`list_*` returns pages, `get_*` returns one, `search_*` takes a query). +- When tools span several services or resources, prefix the name with the service and + then the resource (`asana_search`, `asana_projects_search`). MCP allows 1 to 128 + characters: letters, digits, `_`, `-`, and `.`. Runtype rewrites names before the + model sees them (see "Names as the model sees them" below), so test the final form. - One casing convention for every parameter in the set. - Parameter names say what the value is, not how it is used internally (`recipientEmail`, not `to`). @@ -178,7 +198,8 @@ variation; it never widens a constrained enum or bypasses validation. as `who_am_i`, use `{ "type": "object", "properties": {}, "required": [] }`. Wrap a list input in an object property instead of making the root an array. On a runtime tool, the validator flags a string parameter that asks for JSON (named `json`, - `config`, `configuration`, or `payload`, or described as a JSON string) as + `config`, `configuration`, or `payload`, a name that ends in `json`, or a description + that calls it a JSON string) as `TOOL_PARAM_EMBEDDED_JSON_STRING`. - **Names as the model sees them.** Write tool names in lowercase `snake_case`. Before the model sees a name, Runtype lowercases it, replaces every character other than @@ -204,7 +225,9 @@ variation; it never widens a constrained enum or bypasses validation. confirmation amount, an identifier only the user knows), declare it in `config.elicit: { message, requestedSchema, merge: "parameters" }` on an external or custom tool. Runtype removes those fields from the model's schema and asks the user - for them before the call runs. Each requested property is a string, number, integer, + for them before the call runs. Never request a secret this way: MCP forbids form + elicitation for passwords, API keys, access tokens, and payment credentials, and + requires a URL elicitation for them. Each requested property is a string, number, integer, or boolean. The final `parametersSchema` must set `additionalProperties: false`, and each requested property must match its definition there, including whether it is required. diff --git a/skills/tool-design-output/SKILL.md b/skills/tool-design-output/SKILL.md index 0455e9f..30a18e5 100644 --- a/skills/tool-design-output/SKILL.md +++ b/skills/tool-design-output/SKILL.md @@ -1,8 +1,6 @@ --- name: tool-design-output description: 'Design or audit what an agent tool returns: shape and trim payloads, paginate, report partial success, reference files and media, and add next-step hints. Use when tool output bloats the context window.' -user-invocable: true -argument-hint: '[tool whose result shape to design]' --- # Tool Output Design @@ -66,7 +64,7 @@ After: ### Spend tokens deliberately (Token-Efficient Response) -- Essential fields only. Codes over prose where a code is unambiguous. +- Essential fields only. - Truncate long text fields at a documented length and say so (`"bodyTruncated": true`). - Count instead of listing when the agent needs the number, not the items. - Make the expensive part opt-in: `includeBody: false` by default, with the description @@ -141,7 +139,15 @@ failures with reasons, summary counts, and a retry hint for exactly the failed i Files and blobs travel as typed URIs (`resource://files/abc`, with `contentType`, `sizeBytes`, and a name) that other tools resolve. The conversation carries the -reference, not the bytes. Handle expired or missing references with a clear error. +reference, not the bytes. Handle expired or missing references with a clear error. In +MCP, return a `resource_link` content item for this. + +### Declare a structured result + +An MCP tool can declare `outputSchema` and return `structuredContent` that matches it. +The spec says the tool should also return the same JSON as a text content item. Do so +on Runtype: only `content` reaches the model, so a result with `structuredContent` and +no text block gives the model nothing. ### One vocabulary across the set (Canonical Tool Model) @@ -176,6 +182,8 @@ For error shapes, retry classification, and step failure defaults, see `transform-data` output, and `outputMapping` to select a dot path inside it. A `_`-prefixed variable is rejected, and a variable the flow never assigned fails the tool call. See [Flow tools](https://docs.runtype.com/developer-guides/guides/runtime-tools#flow-tools). +- Only the `content` of an MCP result reaches the model, not `structuredContent`. Always + include a text content item. - If you run your own MCP server, apply these rules to its results. You cannot reshape a third-party MCP server's results, so prefer its narrower tools. - `paginate-api` is the platform's pagination step for upstream lists (cursor, offset, diff --git a/skills/tool-design-security/SKILL.md b/skills/tool-design-security/SKILL.md index d7017a2..cae9bc6 100644 --- a/skills/tool-design-security/SKILL.md +++ b/skills/tool-design-security/SKILL.md @@ -1,8 +1,6 @@ --- name: tool-design-security description: "Design or audit a tool's trust boundary: keep API keys and tenant ids out of model-visible parameters, resist prompt injection, enforce permissions and approval gates in code, declare scopes, and log calls safely." -user-invocable: true -argument-hint: '[tool or toolkit whose trust boundary to design]' --- # Tool Security and Context Design @@ -12,6 +10,9 @@ to call the wrong tool with the wrong arguments and will produce a persuasive re for doing so. The only defenses that hold are the ones the tool layer enforces without consulting the model. +Tool results are a common way in. A result can carry text that a user or a third party +wrote, and the model reads it in the same context as your instructions. + ## Procedure 1. **Name the principal.** Who is the tool acting as: a user, a service account, an @@ -28,6 +29,12 @@ consulting the model. ## Rules with examples +### Treat tool results as untrusted data + +Sanitize tool output and validate it before it reaches the model. Mark results that +carry user-authored or third-party text. A result never authorizes the next action: an +instruction found in a result gets the same permission checks as any other call. + ### Secrets never pass through the model (Secret Injection) Before (the key is in the schema, so it is in the prompt, the trace, and the transcript): @@ -82,6 +89,11 @@ an `authRequired` error that names the missing scope and how to re-authenticate. the narrowest scope that works; different tools in the same set can require different scopes. +An MCP server over HTTP reports a missing scope at run time with `403 Forbidden` and a +`WWW-Authenticate: Bearer error="insufficient_scope"` header. The header's `scope` +parameter lists every scope the operation needs, in one challenge, and the client runs +step-up authorization to get them. + ### Every call is logged (Audit Trail) Record what (tool name, parameters with secrets and PII redacted), who (principal, @@ -98,10 +110,16 @@ Cache it for the session. Downstream tools reference the ids it returns. ### State across calls is explicit (Session Context) -When tools share working state (current project, selected account, scope), store it -server-side against the session, expose tools to set and read it, expire stale sessions, -and echo the active context in results so the agent and the user can see what scope a -call ran in. +MCP revision 2026-07-28 removed protocol sessions. When tools share working state +(current project, selected account, scope), have the server mint an opaque handle and +pass it as an argument to the calls that use it: + +- A handle names state. It does not authenticate the caller, so check authorization + on every call that uses it. +- State how long a handle lives. An expired handle returns a tool execution error that + says how to get a new one. +- Echo the active context in results so the agent and the user can see what scope a + call ran in. ### Inject what the agent would not think to ask for (Context Injection) @@ -147,13 +165,18 @@ Violations return a clear, logged error. `iss` to its own customer's org, because every org shares the signing key. - **Secrets.** `{{secret:KEY}}` references resolve from the managed secret store at execution and are the only credential contract. They resolve in `external` tool - `url`, `headers`, `body`, and auth; in the HTTP flow steps (`fetch-url`, `api-call`, + `url`, `headers`, and `body`; in the HTTP flow steps (`fetch-url`, `api-call`, `wait-until`, `paginate-api`); and in custom MCP server auth (`token`, `username`, `password`, `headers` values, and OAuth client credentials). They do not resolve in prompts, code, or a saved MCP tool's config. Full list: https://docs.runtype.com/user-guide/settings/managing-secrets - - A runtime tool of any other type (`custom`, `flow`, `local`) that contains a secret - reference is rejected with 400. Move the credential into an `external` tool. + - For an `external` tool, put the credential in a header, for example + `"Authorization": "Bearer {{secret:KEY}}"`. No executor reads an auth field on an + `external` tool. + - A runtime tool of any other type (`custom`, `flow`, `local`) that contains a + `{{secret:KEY}}` reference is rejected with 400. A `custom` tool can instead declare + managed secrets in `config.secrets`, which needs `SECRETS:READ`. Otherwise, move the + credential into an `external` tool. - An API key that dispatches runtime tools with secret references needs `SECRETS:READ` (or `SECRETS:*`), or the request fails with 403. - Before a run, call `check_secrets` with the referenced keys to confirm none is @@ -171,10 +194,11 @@ Violations return a clear, logged error. - **Local tools.** A `local` tool runs in the caller's client (SDK or Persona), outside your server. Put no credentials or authorization decisions in it, and treat its result as untrusted input. Enforce permissions in an `external` tool or your own backend. -- **Boundaries.** Cap calls with `tools.maxToolCalls` (1 to 100 per execution) and bound - the loop with `loopConfig.maxTurns` or `loopConfig.maxCost`. For expensive or - destructive tools, enforce a per-tool budget inside the tool; do not set - `tools.perToolLimits`, which is retired and gets the agent rejected. Runtype caps a +- **Boundaries.** Cap calls with `tools.maxToolCalls` (1 to 100 per turn). A call past + the cap gets the tool error `Tool call limit of N reached`. Bound the loop with + `loopConfig.maxTurns` or `loopConfig.maxCost`. For expensive or destructive tools, + enforce a per-tool budget inside the tool. Do not set `tools.perToolLimits`: it is + retired. A save reports it as an advisory, and dispatch refuses the agent. Runtype caps a request's serialized `runtimeTools` at 1 MB and does not cap the tool count, so a smaller tool set is not an injection defense. Pin the host in an external tool's `url` instead of accepting it as a parameter. @@ -191,12 +215,14 @@ Violations return a clear, logged error. `DELETE /v1/tool-approval-grants/{id}`. Review them when you tighten a tool. - The approver answers with `POST /v1/dispatch/approve` (or `POST /v1/agents/{id}/approve` for a saved agent). - - Approval needs someone to answer it. API dispatch and agent execute wait for the - approve call, and Slack, Telegram, SMS, and iMessage surfaces running a multi-turn - agent collect the decision in the conversation. Client-token (Persona) chat and - product chat refuse approval-gated agents with 501 `APPROVAL_MODE_UNSUPPORTED`, - except a root gate with `tools.approval.approver: "end-user"`, which the Persona - visitor approves in the widget. Use `end-user` only when the gate asks for the + - Approval needs someone to answer it. API dispatch, agent execute, and the Product + API wait for the approve call. AG-UI answers through an interrupt and `resume[]`. + Slack, Telegram, SMS, and iMessage surfaces running a multi-turn agent collect the + decision in the conversation. + - Product chat refuses every approval-gated agent with 501 + `APPROVAL_MODE_UNSUPPORTED`. Client-token (Persona) chat refuses them too, except a + root gate with `tools.approval.approver: "end-user"`, which the Persona visitor + approves in the widget. Use `end-user` only when the gate asks for the visitor's own consent (confirming their order, booking, or message). Keep `owner` for gates that enforce your policy or budget (refunds, discounts, credits, spend on your account): the visitor must not grant those to themselves. @@ -204,6 +230,9 @@ Violations return a clear, logged error. and neither can Slack, Telegram, SMS, or iMessage for a single-pass agent. Watch for the `APPROVAL_UNANSWERABLE_ON_SURFACE` warning when you save an agent or bind it to a surface; on those surfaces, remove the gate and enforce the rule in the tool. + - A2A and Product MCP surfaces also refuse a run that reaches an approval gate, and + Claude Managed agents return 501. These surfaces do not raise the save warning, so + check gated agents on them yourself. - Approval covers only tool calls a model chooses in an agent or a prompt step. A flow Tool Call step has no approval gate and always runs. - **Session context.** Keep per-conversation working state (current project, selected @@ -212,8 +241,9 @@ Violations return a clear, logged error. `config.memory.enabled`) only for facts and preferences that must survive across sessions, and scope it with `config.memory.profileTemplate` (for example `{{_endUser.id}}`) so one end user's state never reaches another. An agent with a - `tenancyStrategy` ignores `profileTemplate` and scopes memory to the tenant and end - user itself. + `tenancyStrategy` ignores `profileTemplate` and scopes memory by the strategy's + `dataScope`: per agent for `product`, per tenant for `tenant`, and per end user for + `end-user`. - **Audit.** Every tool call is traced on the run (`trace_execution`, `list_logs`). Values of parameters listed in `hiddenParameterNames` are redacted in tool-input events; every other argument is recorded as sent, so keep PII and secrets out of diff --git a/skills/tool-design/SKILL.md b/skills/tool-design/SKILL.md index 1b41a74..a5b3858 100644 --- a/skills/tool-design/SKILL.md +++ b/skills/tool-design/SKILL.md @@ -1,8 +1,6 @@ --- name: tool-design description: 'Design or audit the tools an AI agent calls (MCP server tools, function calling, Runtype runtime and saved tools), or find out why an agent picks the wrong tool or misuses one. Routes naming, schema, output, error, execution, and security work to focused guides.' -user-invocable: true -argument-hint: '[tool or tool set to design or review]' --- # Tool Design @@ -43,7 +41,7 @@ shapes, and error messages are the only orchestration layer there is. ## Procedure: design a new tool -1. **Classify it** on the three axes and write the answers down before writing a schema: +1. **Classify it** on the four axes and write the answers down before writing a schema: - Type: `query` (read-only, retryable, cacheable), `command` (side effects, document irreversibility), or `discovery` (reveals what exists, schema, capabilities). - Integration: API, database, file system, or system operation. Databases and @@ -51,7 +49,11 @@ shapes, and error messages are the only orchestration layer there is. - Access pattern: synchronous (most tools; bounded seconds), async job (minutes; return a job id), streaming, or event-driven. - Maturity: start **atomic**. Move to enhanced, composite, or orchestrated only - when traces show the signal (see "Level up on evidence"). + when traces show the signal (see "Level up on evidence"). Atomic does not mean + one tool per API endpoint. Anthropic recommends a tool that matches a task, such + as `search_contacts` or `schedule_event`, over thin wrappers such as + `list_contacts`. Start with the smallest task-shaped tool, and add composites + only on evidence. 2. **Write the interface** with `tool-design-interface`: a verb-object name, a description that says when to use it and when not to, constrained parameters, smart defaults, natural identifiers, and dependency hints. @@ -114,7 +116,9 @@ Start atomic and watch traces. Each signal maps to a specific move: | Long-running calls time out | Convert to an async job | Do not build the orchestrated version first. Composite tools built before atomic usage -is understood encode guesses about workflows the agent never runs. +is understood encode guesses about workflows the agent never runs. The trade-off runs +both ways: a set of endpoint-sized tools makes the agent chain calls that one task-sized +tool would answer. ## Pre-ship checklist @@ -134,7 +138,8 @@ Every tool must pass all of these before it reaches an agent: - Invocations are logged with redacted parameters. - Destructive or costly commands are gated (approval, preview mode, or both). -`references/checklist.md` carries the same list with the pattern each row comes from. +`references/checklist.md` carries a longer, numbered version of this list, with the +pattern each row comes from. ## On Runtype @@ -171,8 +176,8 @@ a run handle, and `run_flow` with `async: true` returns an execution id (see The MCP `create_tool` accepts `tool_type` in `flow`, `custom`, `external`, `graphql`, `mcp`, `local`, with `name`, `description`, `parameters_schema` (JSON Schema), and -`config`. `name` is at most 100 characters and `description` at most 500 on create, so -keep the description tight and put detail in parameter descriptions and error text. The +`config`. On create, `name` is at most 100 characters and `description` at most 500. +`update_tool` accepts a description of up to 5,000 characters, but keep the description tight and put detail in parameter descriptions and error text. The REST API and SDKs (`POST /v1/tools`, spelled `toolType` and `parametersSchema`) accept the same set plus `subagent`. To delegate to agents over MCP, pick the route by need: @@ -222,16 +227,17 @@ Iterate with `update_tool` and `get_tool`; read `timeout` in milliseconds, up to 300 s in the tool editor. MCP tools default to 30 s and can run up to 300 s only in background runs. A subagent tool defaults to 5 min. Longer work belongs in an async flow run or a detached subagent. -- Tool set controls: `maxToolCalls` bounds tool-call loops, and `toolCallStrategy` is - `auto`, `required`, or `none`. Do not set `perToolLimits`: it is retired, and an agent - that carries it is rejected. Bound the loop with `loopConfig.maxTurns` or +- Tool set controls: `maxToolCalls` bounds tool calls in one turn, and `toolCallStrategy` + is `auto`, `required`, or `none`. Do not set `perToolLimits`: it is retired. A save + reports it as an advisory, and dispatch refuses the agent. Bound the loop with `loopConfig.maxTurns` or `loopConfig.maxCost`, or enforce a per-tool budget inside the tool. `codeModeConfig` gives the agent a `code_mode` tool that chains a subset of its tools in sandboxed code, an alternative to hand-built bundle and batch tools. - Tool count: no cap; a request's serialized `runtimeTools` may total 1 MB. A provider can still refuse a long list (`TOOL_COUNT_REFUSED_BY_PROVIDER`). Tool search is on by - default for multi-turn agents at 20+ tools (inline tools defer behind `tool_search`, - and `tools.toolSearch.enabled: false` opts out); use it for large tool sets. Single-turn agents send every tool on every + default for multi-turn agents at 20+ capability tools (inline, saved, built-in, and MCP + tools all defer behind `tool_search`, and `tools.toolSearch.enabled: false` opts out); + use it for large tool sets. Single-turn agents send every tool on every request, so keep sets small or split them across agents. - Save-time checks: `validate_flow` reports several checklist rows as stable codes (see `references/checklist.md`, "Checked for you on Runtype"). @@ -279,25 +285,32 @@ Runtype staging and preview deployments only; the production API answers 404 `replay: { synthesize: false }` on the design when the verdict must rest on recordings and deterministic operations only. 6. **Decide on the investment card.** The report's `investment` section reads - Recommended only when no deciding conversation rested on a synthesized answer and - the synthesized share is under the threshold (25% by default); otherwise Indicative, - with the reason. Record the missing calls live or add a deterministic operation, + Recommended only when all three hold: the design clearly beats the baseline, the + verdict still holds without the conversations that a synthesized answer decided, and + the synthesized share is at or below the threshold (25% by default). Otherwise it + reads Indicative, with the reason. Record the missing calls live or add a deterministic operation, then rerun. 7. **Hand it over.** `export_simulation_design_brief` returns the Markdown brief: before and after definitions, response mappings, error envelopes, each operation's checklist row and measured effect. Later live runs mark each operation adopted or not; `list_simulation_design_briefs` shows it beside the baseline trend. -The checklist rows map to operations as follows: - -| Checklist rows | Operation | What the design changes | -| ------------------ | ---------------------------------------- | -------------------------------------------------------- | -| 11, 12, 14, 18, 19 | `shape` | Flattens, renames, drops or truncates fields of a result | -| 13 | `paginate` | One cursor style with `items`, `cursor` and `hasMore` | -| 20, 21, 22 | `error_design` | Error class, reason, recovery steps naming the next tool | -| 6, 23 | `accept_identifier` | Accepts a name and resolves it to an id through a lookup | -| 10, 34, 38, 39 | `add_tool` | A bundle, batch, discovery or identity tool | -| 1, 3, 4, 5 | `rename`, `describe`, `schema`, `preset` | Names, descriptions and argument schemas | +Each operation cites one checklist row by default. An operation's `reason.checklistRow` +overrides it: + +| Operation | Default row | What the design changes | +| ------------------- | ----------- | -------------------------------------------------------- | +| `rename` | 1 | A tool or parameter name | +| `describe` | 3 | A description | +| `schema` | 4 | An argument schema | +| `preset` | 5 | Fixes an argument to a value | +| `accept_identifier` | 6 | Accepts a name and resolves it to an id through a lookup | +| `shape` | 11 | Flattens, renames, drops or truncates fields of a result | +| `paginate` | 13 | One cursor style with `items`, `cursor` and `hasMore` | +| `error_design` | 20 | Error class, reason, recovery steps naming the next tool | +| `error_rewrite` | 21 | Rewrites an error's text | +| `add_tool` | 38 | A bundle, batch, discovery or identity tool | +| `hide` | 39 | Removes a tool from the surface | Developer guide: "Design a better tool surface without deploying it" (`/developer-guides/guides/design-tool-surface-in-simulation` on the Runtype docs). diff --git a/skills/tool-design/references/checklist.md b/skills/tool-design/references/checklist.md index 1a0cf6c..b3d3a90 100644 --- a/skills/tool-design/references/checklist.md +++ b/skills/tool-design/references/checklist.md @@ -71,7 +71,7 @@ succeeds either way, so read the response. Enforced at runtime rather than at save time: tool timeouts (row 26; 30 s for runtime custom tools, longer for saved custom, MCP, and subagent tools), the `idempotent` flag and MCP `idempotentHint` / `readOnlyHint` on interrupted turns (row 28), the 1 MB -`runtimeTools` byte budget (row 39; no count cap, and multi-turn agents defer inline -tools at 20+), `{{secret:KEY}}` +`runtimeTools` byte budget (row 39; no count cap, and multi-turn agents defer +capability tools at 20+, whether inline, saved, built-in, or MCP), `{{secret:KEY}}` resolution (row 30), `hiddenParameterNames` with `_endUser` or `_tenant` (rows 34 and 35), and approval gates (row 37). diff --git a/skills/tool-design/references/pattern-index.md b/skills/tool-design/references/pattern-index.md index daf8449..3a9d764 100644 --- a/skills/tool-design/references/pattern-index.md +++ b/skills/tool-design/references/pattern-index.md @@ -3,6 +3,17 @@ All 54 tool design patterns, grouped by the skill that owns them. Use this to find the skill for a named pattern. +## Contents + +- [tool-design (classification and cross-cutting rules)](#tool-design-classification-and-cross-cutting-rules) +- [tool-design-interface](#tool-design-interface) +- [tool-design-output](#tool-design-output) +- [tool-design-errors](#tool-design-errors) +- [tool-design-execution](#tool-design-execution) +- [tool-design-security](#tool-design-security) +- [tool-design-composition](#tool-design-composition) +- [Quick reference by question](#quick-reference-by-question) + ## tool-design (classification and cross-cutting rules) | Pattern | Intent |