@noodleseed/one 0.136.0 → 0.137.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -52,7 +52,7 @@ export const BUNDLED_EXAMPLE_FILES = [
52
52
  { relPath: "examples/acme-tasks/src/views/widget-style.css", content: ":root {\n color-scheme: light dark;\n font-family:\n Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n --nw-bg: #ffffff;\n --nw-surface: #f7f5ff;\n --nw-text: #1c1830;\n --nw-muted: #635d80;\n --nw-border: #e2ddf5;\n --nw-accent: #7c3aed;\n --nw-accent-strong: #6d28d9;\n --nw-accent-soft: #efe9ff;\n --nw-high: #dc2626;\n --nw-medium: #b45309;\n --nw-low: #2563eb;\n --nw-radius: 10px;\n --nw-shadow: 0 18px 50px rgb(30 20 60 / 12%);\n}\n\n.dark,\n[data-theme=\"dark\"] {\n --nw-bg: #161228;\n --nw-surface: #1d1735;\n --nw-text: #f2eeff;\n --nw-muted: #a99fce;\n --nw-border: #342a54;\n --nw-accent: #a78bfa;\n --nw-accent-strong: #8b5cf6;\n --nw-accent-soft: #2a2148;\n --nw-high: #f87171;\n --nw-medium: #fbbf24;\n --nw-low: #60a5fa;\n --nw-shadow: 0 18px 50px rgb(0 0 0 / 32%);\n}\n\n* {\n box-sizing: border-box;\n}\n\nbody {\n margin: 0;\n background: var(--nw-bg);\n color: var(--nw-text);\n}\n\nbutton,\ninput,\nselect {\n font: inherit;\n}\n\n.nw-shell {\n min-height: 100vh;\n padding: 14px;\n background: var(--nw-bg);\n color: var(--nw-text);\n}\n\n.nw-card {\n max-width: 620px;\n margin: 0 auto;\n background: var(--nw-surface);\n border: 1px solid var(--nw-border);\n border-radius: var(--nw-radius);\n box-shadow: var(--nw-shadow);\n overflow: hidden;\n}\n\n.nw-header {\n display: flex;\n align-items: center;\n gap: 12px;\n padding: 16px;\n border-bottom: 1px solid var(--nw-border);\n}\n\n.nw-icon svg {\n width: 24px;\n height: 24px;\n fill: none;\n stroke: var(--nw-accent);\n stroke-width: 2;\n stroke-linecap: round;\n stroke-linejoin: round;\n}\n\n.nw-title-block {\n flex: 1;\n min-width: 0;\n}\n\n.nw-title {\n margin: 0;\n font-size: 17px;\n font-weight: 700;\n}\n\n.nw-subtitle {\n margin: 2px 0 0;\n font-size: 13px;\n color: var(--nw-muted);\n}\n\n.nw-chip {\n padding: 4px 10px;\n border-radius: 999px;\n background: var(--nw-accent-soft);\n color: var(--nw-accent-strong);\n font-size: 12px;\n font-weight: 600;\n}\n\n.nw-capture {\n display: flex;\n gap: 8px;\n padding: 14px 16px 4px;\n}\n\n.nw-input {\n flex: 1;\n padding: 9px 12px;\n border: 1px solid var(--nw-border);\n border-radius: 10px;\n background: var(--nw-bg);\n color: var(--nw-text);\n}\n\n.nw-button {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 9px 14px;\n border: 1px solid var(--nw-border);\n border-radius: 10px;\n background: var(--nw-bg);\n color: var(--nw-text);\n cursor: pointer;\n}\n\n.nw-button-primary {\n background: var(--nw-accent);\n border-color: var(--nw-accent);\n color: #ffffff;\n font-weight: 600;\n}\n\n.nw-button-primary:disabled {\n opacity: 0.6;\n cursor: default;\n}\n\n.nw-list {\n list-style: none;\n margin: 0;\n padding: 8px 16px 4px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.nw-task {\n display: flex;\n align-items: center;\n gap: 10px;\n padding: 10px 12px;\n border: 1px solid var(--nw-border);\n border-radius: 12px;\n background: var(--nw-bg);\n}\n\n.nw-task-title {\n flex: 1;\n min-width: 0;\n}\n\n.nw-task-done {\n opacity: 0.55;\n}\n\n.nw-task-done .nw-task-title {\n text-decoration: line-through;\n}\n\n.nw-check {\n width: 22px;\n height: 22px;\n border: 1.5px solid var(--nw-border);\n border-radius: 999px;\n background: transparent;\n color: #ffffff;\n cursor: pointer;\n flex: none;\n}\n\n.nw-check-on {\n background: var(--nw-accent);\n border-color: var(--nw-accent);\n}\n\n.nw-priority {\n padding: 5px 8px;\n border: 1px solid var(--nw-border);\n border-radius: 8px;\n background: var(--nw-bg);\n color: var(--nw-text);\n font-size: 12px;\n font-weight: 600;\n}\n\n.nw-priority-high {\n color: var(--nw-high);\n}\n\n.nw-priority-medium {\n color: var(--nw-medium);\n}\n\n.nw-priority-low {\n color: var(--nw-low);\n}\n\n.nw-note {\n margin: 0;\n padding: 8px 16px 16px;\n font-size: 12px;\n color: var(--nw-muted);\n}\n" },
53
53
  { relPath: "examples/acme-tasks/test/server.test.ts", content: "import { describe, expect, it } from 'vitest';\nimport app from '../src/server.js';\n\ndescribe('acme-tasks example', () => {\n it('exports a Noodle server definition', () => {\n expect(typeof app.toManifest).toBe('function');\n });\n\n it('exposes a tool for each of the top-3 prioritized flows', async () => {\n // Capture → add_task, Prioritize → list_today (+ set_priority helper), Complete → complete_task.\n const text = JSON.stringify(await app.toManifest());\n expect(text).toContain('add_task');\n expect(text).toContain('list_today');\n expect(text).toContain('complete_task');\n expect(text).toContain('set_priority');\n });\n\n it('seeds today’s list highest-priority first', async () => {\n const text = JSON.stringify(await app.toManifest());\n expect(text).toMatch(/\"tasks\":\\[\\{\"id\":\"email_vendor\".*\"priority\":\"high\"/);\n });\n\n it('opts the conversational completion action into runtime confirmation', async () => {\n const manifest = await app.toManifest();\n const completeTask = manifest.tools.find((candidate) => candidate.name === 'complete_task');\n const addTask = manifest.tools.find((candidate) => candidate.name === 'add_task');\n const setPriority = manifest.tools.find((candidate) => candidate.name === 'set_priority');\n\n expect(completeTask?.annotations?.confirm).toBe(true);\n expect(addTask?.annotations).not.toHaveProperty('confirm');\n expect(setPriority?.visibility).toEqual(['app']);\n });\n\n it('teaches its three product workflows through one host-neutral agent guide', async () => {\n const manifest = await app.toManifest();\n const guide = manifest.server.agentGuide;\n\n expect(guide?.workflows.map((workflow) => workflow.id)).toEqual([\n 'review_tasks',\n 'capture_task',\n 'complete_task',\n ]);\n expect(\n guide?.workflows.flatMap((workflow) => workflow.steps.map((step) => step.capability.name)),\n ).toEqual(expect.arrayContaining(['list_today', 'set_priority', 'add_task', 'complete_task']));\n expect(\n guide?.workflows\n .find((workflow) => workflow.id === 'review_tasks')\n ?.steps.map((step) => step.capability.name),\n ).toContain('set_priority');\n expect(\n guide?.examples.every((example) =>\n guide.workflows.some((workflow) => workflow.id === example.workflow),\n ),\n ).toBe(true);\n expect(guide?.boundaries.some((boundary) => boundary.toLowerCase().includes('confirm'))).toBe(\n true,\n );\n });\n});\n" },
54
54
  { relPath: "examples/acme-tasks/vitest.config.ts", content: "import { defineConfig } from 'vitest/config';\n\n// Local config so `npm test` (vitest run) discovers this example's own tests instead of inheriting a\n// parent monorepo config's include globs.\nexport default defineConfig({\n test: { include: ['test/**/*.test.ts'] },\n});\n" },
55
- { relPath: "examples/customer-auth/README.md", content: "# Customer Auth - OIDC identity and customer-routed APIs\n\nThis curated example owns the customer/end-user authentication capability slot. It proves that a SaaS app\ncan protect an MCP endpoint with direct OIDC, retain role/scope-based tool authorization, and route ordinary\nreads and confirmed actions to the API origin selected by the verified customer's identity provider.\n\nIt also owns the customer-branded embedded-assistant presentation showcase. Direct MCP calls obtain the\nroute from the verified OIDC claim; embedded sessions obtain it from the authenticated customer backend's\nsession exchange. Both paths keep the URL outside tool/model/browser-visible state.\n\nThe public developer entrypoint is [`src/server.ts`](src/server.ts). It exposes a deliberately small MCP\nsurface for organization discovery and app lifecycle operations:\n\n- `list_my_organizations` lists the NoodleSeed.com organizations the signed-in customer belongs to (no\n arguments — the org set comes from the verified customer session).\n- `list_org_apps` lists apps for one of those organizations through that tenant's API. It is visible and\n callable only when the verified customer has the `org_apps:read` scope and either the `org_admin` or\n `org_member` role.\n- `archive_org_app` archives one app only after exact runtime confirmation. It requires the\n `org_apps:write` scope and `org_admin` role.\n\nThe tools chain: `list_my_organizations` surfaces the `org_id`s the customer can act on,\n`list_org_apps` takes one of those ids, and `archive_org_app` accepts the selected app id. Tool code remains\nindependent of the selected origin.\n\nThe server also declares one typed `agentGuide` for those product workflows. The deployed embedded assistant\nuses it automatically: each turn keeps only complete workflows supported by the verified session's roles,\nscopes, and model-visible tools. An organization member can receive organization/app review guidance, while\nonly an administrator with `org_apps:write` receives the complete archive workflow and its confirmation\nboundary. The guide stays server-side, so the Web Component, React renderer, headless hook, and public client\nneed no new option and receive no raw skill content. See\n[using a product guide at runtime](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime)\nfor the public behavior guide.\n\nA skill-aware external agent connected directly to the same tenant MCP URL receives the same\ncomplete-workflow filtering through the modern draft MCP Skills extension. Members and administrators may\ntherefore receive different `SKILL.md` and MCP-surface bytes, each with matching caller-specific digests.\nThis reuses the configured customer OAuth boundary; it does not require a second skill installation or auth\nsystem, and it is not a claim that every external host currently implements the draft extension. The\nsame [runtime guide](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime)\nexplains this preview boundary.\n\n## Declare the customer endpoint\n\n`customerEndpoint` names one private routing authority and bounds the origins an IdP may select:\n\n```ts\nconst customerApi = customerEndpoint('customer_api', {\n allowedHttpsHostSuffixes: ['api.noodleseed.dev'],\n});\n```\n\nUse either non-empty `allowedHttpsHostSuffixes` or non-empty `allowedHttpsOrigins`, never both. Exact-origin\npolicies may include a non-default port. Suffix policies match only the exact hostname or dot-boundary\nsubdomains on port 443. A routed connector must not add `allowedOrigins`; its endpoint policy is the egress\nallowlist.\n\nThe connector uses that declaration as its normal base URL. Its token endpoint remains a fixed, independently\nvalidated HTTPS URL:\n\n```ts\nconst api = connector('noodleseed_app_api')\n .version('1.0.0')\n .http({\n baseUrl: customerApi,\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: variable('CUSTOMER_API_CLIENT_ID'),\n clientSecret: secret('CUSTOMER_API_CLIENT_SECRET'),\n scopes: ['organizations:read', 'org_apps:read', 'org_apps:write'],\n audience: 'noodleseed-customer-api',\n },\n operations: {\n // read and action operations...\n },\n });\n```\n\n`delegatedTokenExchange` consumes a verified customer caller; an MCP access mode does not create one. The\nserver must declare `customerAuth.*(...)` or `embeddedAssistant(...)` so Noodle Seed can establish the caller\nsubject, issuer, and audience. Otherwise `noodle validate`, `noodle auth doctor`, and deploy fail early with\n`delegated_token_exchange_identity_required`, before secrets are resolved or any connector egress. A\nsuccessful local Devtools exchange is not evidence that the hosted server has an identity source. Devtools\nsupplies a separate, loopback-only local identity context that is never accepted by hosted deployment.\n\nAt both connector and operation level, auth must be omitted or use `delegatedTokenExchange`. The compiler\nvalidates the concrete connector definition emitted from TypeScript, including connector defaults and\noperation overrides, and reports the exact failing auth path and kind. Do not keep a bearer, API-key,\nclient-credentials, or managed-provider fallback for local mode; use operation fakes while leaving auth\ndeclarative.\n\n## Map the endpoint from verified OIDC\n\nThe IdP claim contains the complete base URL, including an optional base path. Routing is separate from the\npublic `${user}` expression scope:\n\n```ts\nauth: customerAuth.oidc({\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n}),\n```\n\nFor federated OIDC, put the same endpoint map on every issuer. Claim paths may differ, but each issuer must\nmap every endpoint the app uses:\n\n```ts\nauth: customerAuth.federatedOidc({\n issuers: [\n {\n issuer: 'https://id.customer-a.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n },\n {\n issuer: 'https://login.customer-b.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'organization.routes.customer_api' },\n },\n },\n },\n ],\n}),\n```\n\nAt runtime, Noodle Seed validates the configured stable audience, associates the caller with the exact\ntransport-derived MCP resource, projects the route into private request state, applies its policy, and\nfreezes it for the call. Missing, malformed, or\ndisallowed claims return `connector_route_unavailable` before credential lookup or connector egress.\nResolved URLs never enter artifacts, `${user}`, logs, model output, widgets, public confirmation review,\nbroker cache keys, or delegated exchange assertions.\n\nRouted reads work in tools, including declared nested calls. Routed actions require exact\n`annotations.confirm: true`; otherwise they fail with `customer_endpoint_action_unsupported`. Routed\nresources, prompts, and ambient context fail with `customer_endpoint_surface_unsupported`.\n\nThe flagship's routed action uses the normal TypeScript action helper:\n\n```ts\ntool('archive_org_app', {\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n annotations: annotations.openAction({ destructive: false, confirm: true }),\n // input, output, and the normal connectors.app_api.archiveOrgApp(...) call...\n});\n```\n\nThe flagship also opts into the current stateless hosted MCP path:\n\n```ts\ninteractions: {\n confirmationFallback: 'host',\n},\n```\n\nA bidirectional client that negotiated form elicitation can complete the standard confirmation exchange\ninstead. The explicit host fallback trusts the MCP host to have collected native write approval before the\ntool call reaches Noodle Seed; it is never inferred from client identity and does not replace auth, policy,\nor accurate action/destructive annotations. Omit the fallback when connected hosts are not trusted to\nprovide that approval. If neither standard confirmation nor the fallback is available, the action fails\nclosed with `interaction_unavailable`.\n\nPreparation stores only sorted route `{ key, fingerprint }` bindings in its private server-held\ncontinuation; the public review exposes none of them. Acceptance re-resolves the current request route and\nreturns `invalid_continuation` if it is missing or changed, before policy, credentials, or egress. A match\nreuses the current frozen snapshot for the action and all nested or later reads.\n\nThe application developer owns the direct/federated authorization server. It must publish its path-inserted\nRFC 8414 document as direct HTTP 200 JSON with exact issuer and HTTPS authorization/token/registration/JWKS\nendpoints, authorization-code and refresh grants, PKCE S256, public-client auth method `none`, RFC 8707\nresource handling, and public signing keys. It validates each exact MCP resource on authorize, code exchange,\nand refresh, then maps approved versions of this app/environment to `noodleseed-customer-auth-prod`. Other\napps and environments use distinct audiences.\n\nRun `noodle auth doctor src/server.ts` before sharing. Its bounded, read-only probes never register a client.\nAdding the embedded assistant does not choose or rewrite MCP customer auth. Its authenticated backend may\nbind `routing.endpoints.customer_api` during assistant-session exchange from server-owned membership data;\ndirect MCP requests continue to resolve the same endpoint from the configured verified OIDC claim.\n\n## Per-tool authorization remains independent\n\nThe mapped `roles` and `scopes` paths are read only after OIDC verification. The restricted tool declares its\nrule beside the rest of its public contract:\n\n```ts\ntool('list_org_apps', {\n authorization: {\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n },\n // input, output, and fulfilment...\n});\n```\n\nEvery required scope must be present and at least one allowed role must match. When both lists are declared,\nboth conditions apply. Route availability never changes `tools/list`: discovery remains based only on\nroles/scopes. A restricted tool is omitted for an ineligible customer and a guessed direct call still fails\nclosed.\n\nTool code calls the connector normally:\n\n```ts\nfulfil({ input, connectors }) {\n const apps = connectors.app_api.listOrgApps({\n org_id: input.org_id,\n skip: input.skip,\n limit: input.limit,\n });\n\n return { result: apps.result };\n}\n```\n\nThe broker exchanges a short-lived, platform-signed assertion at the fixed token endpoint and caches the\nresult by caller, connector, scopes, and a route fingerprint. The assertion carries only the route key and\nfingerprint, never the URL. The MCP access token is never forwarded to the customer API. The exchange wire\ncontract lives in docs/spec/connectors.md.\n\nFirebase and Microsoft remain supported managed adapters; their provider-specific contracts and tests live\nin docs/spec/auth-and-policy.md and the SharePoint flagship.\n\n## Supabase direct-OIDC access-token hook\n\nDynamic Client Registration lets any OAuth client register, so the presence of `client_id` is not approval.\nKeep an operator-controlled client-to-audience map and rewrite `aud` only for an exact mapped client. For a\ndynamically registered client, review its generated client ID, name, and exact redirect URIs in the consent\nflow before adding the mapping. Each new registration needs its own row; never approve by name or prefix.\n\nReplace `<approved-oauth-client-id>` with the reviewed client ID and `<stable-mcp-audience>` with the exact\nvalue configured in `customerAuth.oidc`:\n\n```sql\ncreate table if not exists public.mcp_oauth_client_audiences (\n client_id text primary key check (btrim(client_id) <> ''),\n audience text not null check (btrim(audience) <> '')\n);\n\nrevoke all on table public.mcp_oauth_client_audiences from authenticated, anon, public;\ngrant usage on schema public to supabase_auth_admin;\ngrant select on table public.mcp_oauth_client_audiences to supabase_auth_admin;\n\ninsert into public.mcp_oauth_client_audiences (client_id, audience)\nvalues ('<approved-oauth-client-id>', '<stable-mcp-audience>')\non conflict (client_id) do update set audience = excluded.audience;\n\ncreate or replace function public.mcp_access_token_hook(event jsonb)\nreturns jsonb\nlanguage plpgsql\nstable\nas $$\ndeclare\n claims jsonb := coalesce(event->'claims', '{}'::jsonb);\n oauth_client_id text := nullif(btrim(claims->>'client_id'), '');\n mapped_audience text;\nbegin\n if oauth_client_id is not null then\n select mapping.audience\n into mapped_audience\n from public.mcp_oauth_client_audiences as mapping\n where mapping.client_id = oauth_client_id;\n end if;\n\n if mapped_audience is not null then\n claims := jsonb_set(\n claims,\n '{aud}',\n to_jsonb(mapped_audience),\n true\n );\n end if;\n\n return jsonb_build_object('claims', claims);\nend;\n$$;\n\ngrant execute on function public.mcp_access_token_hook(jsonb) to supabase_auth_admin;\nrevoke execute on function public.mcp_access_token_hook(jsonb) from authenticated, anon, public;\n```\n\n| Token source | Mapping | Resulting `aud` |\n| --- | --- | --- |\n| Approved OAuth client | Exact client row | Mapped stable MCP audience |\n| Unrelated or unknown OAuth client | No row | Original Supabase audience |\n| Browser session | No `client_id` | Original Supabase audience |\n\nSelect this function under Supabase Auth Hooks before completing the interactive verification below.\n\n## Validate\n\n```bash\nnoodle validate examples/customer-auth/src/server.ts --json\nnoodle auth doctor examples/customer-auth/src/server.ts --json\nnoodle test examples/customer-auth/src/server.ts --json\n```\n\nThe doctor proves metadata and JWKS readiness without registering a client. For this protected app,\n`noodle test` proves the anonymous 401 plus exact protected-resource metadata boundary and reports\n`interactiveRequired: true`; neither command proves token issuance or audience verification.\n\nAgainst a deployed customer-protected environment, set a short-lived real customer token only in\n`NOODLE_CUSTOMER_TOKEN` and add `--live --org <org> --app <app> --env <env>`. The live doctor performs\ncredential exchanges without invoking any business tool. Add `--version 1` when testing a pinned version;\nthe reported customer resource must match that versioned MCP endpoint.\n\n## Run locally\n\n```bash\nnoodle devtools examples/customer-auth/src/server.ts\n```\n\nComplete sign-in in Devtools and load the tool list. That authenticated request is the local proof that DCR,\nPKCE, token issuance, issuer/signature verification, the stable audience, and exact-resource binding work\ntogether. Invoke a representative safe read when the configured customer API is available.\n\n### Test delegated exchange locally\n\nLocal customer OIDC sign-in and delegated-exchange assertion trust are two distinct boundaries. OIDC proves\nthe caller to the local MCP server; Devtools uses a separate local issuer only for the RFC 8693 assertion\nsent to the downstream token endpoint. This is the canonical local path and requires no `server.ts` change,\nflag, environment variable, or config surface.\n\n1. Configure the OIDC authorization server for the exact loopback callback and RFC 8707 resource. Do not add\n the Devtools assertion key to OIDC issuer metadata or change its signing keys.\n2. Start Devtools, complete customer sign-in, and copy the displayed `{ issuer, jwks }` from **Local delegated exchange**.\n3. Pin both values only in the customer-owned development RFC 8693 token endpoint.\n4. Restrict that trust to development client credentials, audience, API, and data.\n5. Invoke the delegated `list_org_apps` tool until its binding reads **Exchange verified**.\n6. Use hosted preview or `noodle auth doctor --live` to prove the production platform issuer.\n\n**Never trust the Devtools issuer in production: anyone holding the local private key could impersonate a customer.**\n\n## Configuration\n\nThe embedded assistant uses a customer-supplied OpenAI Chat Completions-compatible endpoint. Configure its\nmanaged values at the Noodle deployment environment; none of these values belongs in the customer web\napplication environment, and the API key never reaches the browser:\n\nThe assistant session carries a verified user, tenant, deployment, roles, and scopes. For this flagship's\nrouted tools, the embedding backend resolves the signed-in user's cluster from server-owned membership data\nand passes `routing: { endpoints: { customer_api: cluster.apiBaseUrl } }` to\n`createAssistantSession`. Noodle validates and privately stores that route; it is not returned to the\nbrowser. Do not copy the route into page context, session claims, tool input, or model instructions.\n\n```bash\nnoodle variables set ASSISTANT_ORIGIN https://app.example.com --scope env\nnoodle variables set ASSISTANT_MODEL_BASE_URL https://model.example.com/v1 --scope env\nnoodle variables set ASSISTANT_MODEL your-model --scope env\nnoodle secrets set ASSISTANT_MODEL_API_KEY --scope env\nnoodle variables set CUSTOMER_API_CLIENT_ID your-broker-client-id --scope env\nnoodle secrets set CUSTOMER_API_CLIENT_SECRET --scope env\nnoodle check --target embedded-assistant src/server.ts\n```\n\n`ASSISTANT_ORIGIN` is the operator-owned production embedding origin, so one source can serve every customer\nwithout an application fork. Assistant origins are exact. Production embedding origins must use HTTPS; plain HTTP is accepted only for\nloopback development origins such as `http://localhost:3000`, `http://127.0.0.1:3000`, or\n`http://[::1]:3000`. `noodle dev` serves the MCP project, not that separate embedding application.\n\nThe bounded `presentation` object configures the panel, launcher, header, composer, and messages. Its\nprimitives derive colors from shared server `branding`; raw HTML, CSS, inline SVG, renderer classes, and\ncallbacks are not accepted.\n\nCreate the backend credential after deployment. The CLI writes it to a mode-0600 file and never prints the\nsecret:\n\n```bash\nnoodle assistant clients create --name web --org noodleseed --app customer-auth --env prod\n```\n\nOnly the Noodle service URL, assistant client ID, and assistant client secret belong in the authenticated\ncustomer backend. The model URL, model name, and model API key remain managed by the Noodle deployment.\n\nThe customer's authenticated backend calls `createAssistantSession(...)` from\n`@noodleseed/assistant/server`, passing the already-verified user and browser origin. The browser then uses\nthe returned short-lived session through the managed Web Component/React renderer or a customer-owned UI:\n\n```bash\npnpm add @noodleseed/assistant\n```\n\n```tsx\nimport { NoodleAssistant } from '@noodleseed/assistant/react';\n\n<NoodleAssistant\n sessionEndpoint=\"/api/noodle-assistant/session\"\n theme={resolvedTheme}\n onSessionExpired={() => console.info('Assistant session renewed')}\n/>;\n```\n\n`resolvedTheme` is the application's current `'light' | 'dark'` value. Use `theme=\"auto\"` only when the\nbrowser operating-system preference is intentionally authoritative.\n\nFor an entirely application-owned React renderer, use the renderer-free hook. It creates no custom element\nand returns the AI SDK transcript plus the canonical client commands:\n\n```tsx\n'use client';\n\nimport { useEffect, useState } from 'react';\nimport { NoodleAppView } from '@noodleseed/assistant/react';\nimport { useNoodleAssistant } from '@noodleseed/assistant/react/client';\n\nexport function CustomerAssistant({\n principalKey,\n resolvedTheme,\n}: {\n principalKey: string;\n resolvedTheme: 'light' | 'dark';\n}) {\n const [draft, setDraft] = useState('');\n const { client, messages, status, error } = useNoodleAssistant({\n sessionEndpoint: '/api/noodle-assistant/session',\n principalKey,\n });\n const busy = status === 'submitted' || status === 'streaming';\n const settle = (operation: Promise<void>) => {\n void operation.catch(() => {\n // The hook exposes this same structured failure through `error`.\n });\n };\n\n return (\n <section aria-label=\"Assistant\" aria-busy={busy}>\n {messages.map((message) => (\n <article key={message.id} data-role={message.role}>\n {message.parts.map((part, index) => {\n if (part.type === 'text') return <p key={index}>{part.text}</p>;\n if (part.type === 'data-confirmation') {\n const review = part.data;\n return (\n <section key={review.id} aria-label=\"Review proposed action\">\n <h3>{review.title ?? 'Review proposed action'}</h3>\n {review.description ? <p>{review.description}</p> : null}\n <pre aria-label=\"Proposed action arguments\">\n {JSON.stringify(review.arguments ?? {}, null, 2)}\n </pre>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'accept' }))}\n >\n Confirm\n </button>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'decline' }))}\n >\n Don't proceed\n </button>\n </section>\n );\n }\n if (part.type === 'data-input-request') {\n const request = part.data;\n return (\n <section key={request.id} aria-label=\"Assistant needs input\">\n <p>{request.message}</p>\n <p>This renderer has not implemented the requested form.</p>\n <button\n disabled={busy || request.status !== 'pending'}\n onClick={() => settle(client.respond(request.id, { action: 'decline' }))}\n >\n Cancel request\n </button>\n </section>\n );\n }\n if (part.type === 'data-tool-result') {\n return (\n <pre key={part.data.id} aria-label={`${part.data.tool} result`}>\n {JSON.stringify(part.data.result, null, 2)}\n </pre>\n );\n }\n if (part.type === 'data-view') {\n return (\n <NoodleAppView\n key={`${part.data.id}:${part.data.resourceUri}`}\n client={client}\n view={part.data}\n theme={resolvedTheme}\n />\n );\n }\n return <p key={index}>Unsupported assistant content.</p>;\n })}\n </article>\n ))}\n {error ? <p role=\"alert\">{error.message}</p> : null}\n <form\n onSubmit={(event) => {\n event.preventDefault();\n const message = draft.trim();\n if (!message) return;\n setDraft('');\n settle(client.sendMessage(message));\n }}\n >\n <input\n aria-label=\"Message\"\n value={draft}\n onChange={(event) => setDraft(event.currentTarget.value)}\n />\n {busy ? (\n <button type=\"button\" onClick={() => client.abort()}>\n Stop\n </button>\n ) : (\n <button type=\"submit\">Send</button>\n )}\n </form>\n </section>\n );\n}\n```\n\n`principalKey` stays in the browser. Change it whenever the authenticated user or tenant changes; the hook\nthen aborts and clears the prior session and transcript. The sample fails closed on input requests until its\nfallback is replaced with a form generated from `requestedSchema`. A production renderer must show the\ncomplete confirmation review and both decisions. For `data-view`, map `resourceUri` or `tool` and the\nbounded/redacted result to a component already trusted by this application only when intentionally replacing\nthe linked App with a native UI. Otherwise use `NoodleAppView`; JSON result data is not the App UI. Its\nsemantic lifecycle identity is the client plus `view.id` plus `view.resourceUri`, so parent payload/callback\nrerenders keep the iframe and only a different view or unmount tears down the bridge.\nNever inject `part.data.html`, assign it to `srcdoc`, fetch a `ui://` URI, or reproduce the bridge directly. Pages with a\nContent-Security-Policy must include the Noodle service origin in both `connect-src` and `frame-src`.\n\nBefore the production-equivalent host build, run the presence-only handoff check:\n\n```sh\nnoodle assistant embed --check --json\n```\n\nAdd application-owned delegated-exchange requirements with repeatable `--require-env NAME` flags. The JSON\nreports required and missing names, CSP status, and post-deploy probes without returning environment values\nor writing scaffold files. Map the names through the production secret manager, CI environment, and any\nsecret allowlist; regenerate existing framework-owned environment binding types before the build. Default\nDevtools/model exercises to synthetic data, and obtain approval before sending real connector data to an\nexternal model.\n\nAfter deployment, use the assistant doctor to verify the embed client, model, and static session boundary:\n\n```sh\nnoodle assistant doctor --user-id <real-test-user> --origin \"$PUBLIC_APP_ORIGIN\" --org <org> --app <app> --env <env>\n```\n\nThe doctor does not invent or test an application-specific customer route. Prove routed assistant tools by\nhaving the authenticated embedding backend pass the user's server-verified endpoint during session\nexchange, then invoke one representative safe read.\n\nIf the application deliberately sends a first turn on mount, do not combine a persistent \"sent\" ref with a\nmount effect. React Strict Mode can abort that provisional request and then suppress the stable remount.\nSchedule the send after the provisional cleanup and settle its promise:\n\n```tsx\nuseEffect(() => {\n let active = true;\n queueMicrotask(() => {\n if (active) settle(client.sendMessage(initialMessage));\n });\n return () => {\n active = false;\n };\n}, [client, initialMessage]);\n```\n\nFor a chat-first custom host, raw `tool_started` supplies the direct call `id` and technical tool name. Map\nknown tools to concise application copy and use a neutral fallback. Reserve a stable `role=\"status\"` region\nfor thinking, tool activity, and the view skeleton; switch to the ready `NoodleAppView` on `view_available`\nor to `role=\"alert\"` on error. Decorative skeleton shapes stay hidden from assistive technology, and shimmer\nor transition motion is disabled under `prefers-reduced-motion`.\n\nUse `${view.id}:${view.resourceUri}` as transport identity. Different call IDs are distinct invocations and\nmust not be deduplicated generically. If this application intentionally owns one current panel for a known\nresource, declare an application-owned slot for that resource and replace only that slot.\n\nOutside React, subscribe to the DOM-free client directly. It exposes the same conversation as headless AI\nSDK `UIMessage` state, including typed confirmation, input, tool-result, and linked-view parts:\n\n```ts\nimport { createAssistantClient } from '@noodleseed/assistant/client';\n\nconst assistant = createAssistantClient({\n sessionEndpoint: '/api/noodle-assistant/session',\n});\n\nassistant.subscribeChat((state) => {\n renderUIMessageState(state);\n for (const message of state.messages) {\n for (const part of message.parts) {\n if (part.type === 'data-confirmation' && part.data.status === 'pending') {\n renderConfirmation(part.data, (response) => assistant.respond(part.data.id, response));\n }\n }\n }\n});\n```\n\n`theme=\"auto\"` follows the operating-system preference, not a SaaS-owned toggle. Pass the resolved\n`light`/`dark` theme to `NoodleAssistant` and `NoodleAppView`; updates reach mounted MCP Apps without a\nremount. CSS custom properties inherit through the host, and documented `--ns-assistant-*` variables remain\nthe final integration escape hatch. Server `branding` is shared by widgets and the assistant; there is no\nsecond branding declaration. Text streams progressively. Expired turns re-exchange and retry once;\nconfirmations never replay automatically.\n\nThe customer IdP must place the full tenant API base URL in `tenant.api_base_url`. For example, one verified\ncustomer may receive `https://customer-a.api.noodleseed.dev/v1` and another\n`https://customer-b.api.noodleseed.dev/v1`; both satisfy the declared suffix policy. Application code,\ndeployment variables, and connector arguments do not select the tenant route.\n\n`CUSTOMER_API_CLIENT_ID` and `CUSTOMER_API_CLIENT_SECRET` authenticate only the broker to the fixed exchange\nendpoint. They are not customer API bearer tokens. The exchange endpoint verifies the platform-signed\nsubject assertion and mints a short-lived token scoped to the signed-in user and route binding.\n\n## Deploy customer-protected to Noodle Seed Cloud\n\n```bash\nnoodle deploy examples/customer-auth/src/server.ts \\\n --org noodleseed \\\n --app customer-auth \\\n --env prod \\\n --access customers\n```\n\nEndpoint:\n\n```text\nhttps://cloud.noodleseed.dev/o/noodleseed/customer-auth/mcp\n```\n\n## MCP Primitives\n\n- Tool `list_my_organizations`: calls `GET /api/organizations` and returns the organizations the signed-in\n customer is a member of. Takes no arguments; the org set is scoped by the verified customer session.\n- Tool `list_org_apps`: calls `GET /api/organizations/{org_id}/apps` for one organization `org_id`.\n- Tool `archive_org_app`: after confirmation, calls\n `POST /api/organizations/{org_id}/apps/{app_id}/archive`.\n\n## Auth boundary\n\nNoodle Seed verifies the configured OIDC issuer and stable audience, then binds the exact transport-derived\nMCP resource before reading identity or routing claims. Public caller identity contains the user/role/scope\nprojection; the customer route remains private request state.\n\nConnector-backed tools ask the broker for a route-bound delegated credential; only the endpoint key and\nfingerprint enter broker cache/single-flight state or the assertion. The route claim and inbound MCP bearer\ntoken never reach tools, connectors, widgets, model output, or downstream systems. Confirmed actions keep\nthe same URL-blind binding only in private continuation state and reject acceptance-time drift.\n" },
55
+ { relPath: "examples/customer-auth/README.md", content: "# Customer Auth - OIDC identity and customer-routed APIs\n\nThis curated example owns the customer/end-user authentication capability slot. It proves that a SaaS app\ncan protect an MCP endpoint with direct OIDC, retain role/scope-based tool authorization, and route ordinary\nreads and confirmed actions to the API origin selected by the verified customer's identity provider.\n\nIt also owns the customer-branded embedded-assistant presentation showcase. Direct MCP calls obtain the\nroute from the verified OIDC claim; embedded sessions obtain it from the authenticated customer backend's\nsession exchange. Both paths keep the URL outside tool/model/browser-visible state.\n\nThe public developer entrypoint is [`src/server.ts`](src/server.ts). It exposes a deliberately small MCP\nsurface for organization discovery and app lifecycle operations:\n\n- `list_my_organizations` lists the NoodleSeed.com organizations the signed-in customer belongs to (no\n arguments — the org set comes from the verified customer session).\n- `list_org_apps` lists apps for one of those organizations through that tenant's API. It is visible and\n callable only when the verified customer has the `org_apps:read` scope and either the `org_admin` or\n `org_member` role.\n- `archive_org_app` archives one app only after exact runtime confirmation. It requires the\n `org_apps:write` scope and `org_admin` role.\n\nThe tools chain: `list_my_organizations` surfaces the `org_id`s the customer can act on,\n`list_org_apps` takes one of those ids, and `archive_org_app` accepts the selected app id. Tool code remains\nindependent of the selected origin.\n\nThe server also declares one typed `agentGuide` for those product workflows. The deployed embedded assistant\nuses it automatically: each turn keeps only complete workflows supported by the verified session's roles,\nscopes, and model-visible tools. An organization member can receive organization/app review guidance, while\nonly an administrator with `org_apps:write` receives the complete archive workflow and its confirmation\nboundary. The guide stays server-side, so the Web Component, React renderer, headless hook, and public client\nneed no new option and receive no raw skill content. See\n[using a product guide at runtime](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime)\nfor the public behavior guide.\n\nA skill-aware external agent connected directly to the same tenant MCP URL receives the same\ncomplete-workflow filtering through the modern draft MCP Skills extension. Members and administrators may\ntherefore receive different `SKILL.md` and MCP-surface bytes, each with matching caller-specific digests.\nThis reuses the configured customer OAuth boundary; it does not require a second skill installation or auth\nsystem, and it is not a claim that every external host currently implements the draft extension. The\nsame [runtime guide](https://docs.noodleseed.dev/docs/guides/product-agent-guides#use-the-guide-at-runtime)\nexplains this preview boundary.\n\n## Declare the customer endpoint\n\n`customerEndpoint` names one private routing authority and bounds the origins an IdP may select:\n\n```ts\nconst customerApi = customerEndpoint('customer_api', {\n allowedHttpsHostSuffixes: ['api.noodleseed.dev'],\n});\n```\n\nUse either non-empty `allowedHttpsHostSuffixes` or non-empty `allowedHttpsOrigins`, never both. Exact-origin\npolicies may include a non-default port. Suffix policies match only the exact hostname or dot-boundary\nsubdomains on port 443. A routed connector must not add `allowedOrigins`; its endpoint policy is the egress\nallowlist.\n\nThe connector uses that declaration as its normal base URL. Its token endpoint remains a fixed, independently\nvalidated HTTPS URL:\n\n```ts\nconst api = connector('noodleseed_app_api')\n .version('1.0.0')\n .http({\n baseUrl: customerApi,\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: variable('CUSTOMER_API_CLIENT_ID'),\n clientSecret: secret('CUSTOMER_API_CLIENT_SECRET'),\n scopes: ['organizations:read', 'org_apps:read', 'org_apps:write'],\n audience: 'noodleseed-customer-api',\n },\n operations: {\n // read and action operations...\n },\n });\n```\n\n`delegatedTokenExchange` consumes a verified customer caller; an MCP access mode does not create one. The\nserver must declare `customerAuth.*(...)` or `embeddedAssistant(...)` so Noodle Seed can establish the caller\nsubject, issuer, and audience. Otherwise `noodle validate`, `noodle auth doctor`, and deploy fail early with\n`delegated_token_exchange_identity_required`, before secrets are resolved or any connector egress. A\nsuccessful local Devtools exchange is not evidence that the hosted server has an identity source. Devtools\nsupplies a separate, loopback-only local identity context that is never accepted by hosted deployment.\n\nAt both connector and operation level, auth must be omitted or use `delegatedTokenExchange`. The compiler\nvalidates the concrete connector definition emitted from TypeScript, including connector defaults and\noperation overrides, and reports the exact failing auth path and kind. Do not keep a bearer, API-key,\nclient-credentials, or managed-provider fallback for local mode; use operation fakes while leaving auth\ndeclarative.\n\n## Map the endpoint from verified OIDC\n\nThe IdP claim contains the complete base URL, including an optional base path. Routing is separate from the\npublic `${user}` expression scope:\n\n```ts\nauth: customerAuth.oidc({\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n}),\n```\n\nFor federated OIDC, put the same endpoint map on every issuer. Claim paths may differ, but each issuer must\nmap every endpoint the app uses:\n\n```ts\nauth: customerAuth.federatedOidc({\n issuers: [\n {\n issuer: 'https://id.customer-a.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n },\n {\n issuer: 'https://login.customer-b.com',\n audience: 'noodleseed-customer-auth-prod',\n routing: {\n endpoints: {\n customer_api: { claim: 'organization.routes.customer_api' },\n },\n },\n },\n ],\n}),\n```\n\nAt runtime, Noodle Seed validates the configured stable audience, associates the caller with the exact\ntransport-derived MCP resource, projects the route into private request state, applies its policy, and\nfreezes it for the call. Missing, malformed, or\ndisallowed claims return `connector_route_unavailable` before credential lookup or connector egress.\nResolved URLs never enter artifacts, `${user}`, logs, model output, widgets, public confirmation review,\nbroker cache keys, or delegated exchange assertions.\n\nRouted reads work in tools, including declared nested calls. Routed actions require exact\n`annotations.confirm: true`; otherwise they fail with `customer_endpoint_action_unsupported`. Routed\nresources, prompts, and ambient context fail with `customer_endpoint_surface_unsupported`.\n\nThe flagship's routed action uses the normal TypeScript action helper:\n\n```ts\ntool('archive_org_app', {\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n annotations: annotations.openAction({ destructive: false, confirm: true }),\n // input, output, and the normal connectors.app_api.archiveOrgApp(...) call...\n});\n```\n\nThe flagship also opts into the current stateless hosted MCP path:\n\n```ts\ninteractions: {\n confirmationFallback: 'host',\n},\n```\n\nA bidirectional client that negotiated form elicitation can complete the standard confirmation exchange\ninstead. The explicit host fallback trusts the MCP host to have collected native write approval before the\ntool call reaches Noodle Seed; it is never inferred from client identity and does not replace auth, policy,\nor accurate action/destructive annotations. Omit the fallback when connected hosts are not trusted to\nprovide that approval. If neither standard confirmation nor the fallback is available, the action fails\nclosed with `interaction_unavailable`.\n\nPreparation stores only sorted route `{ key, fingerprint }` bindings in its private server-held\ncontinuation; the public review exposes none of them. Acceptance re-resolves the current request route and\nreturns `invalid_continuation` if it is missing or changed, before policy, credentials, or egress. A match\nreuses the current frozen snapshot for the action and all nested or later reads.\n\nThe application developer owns the direct/federated authorization server. It must publish its path-inserted\nRFC 8414 document as direct HTTP 200 JSON with exact issuer and HTTPS authorization/token/registration/JWKS\nendpoints, authorization-code and refresh grants, PKCE S256, public-client auth method `none`, RFC 8707\nresource handling, and public signing keys. It validates each exact MCP resource on authorize, code exchange,\nand refresh, then maps approved versions of this app/environment to `noodleseed-customer-auth-prod`. Other\napps and environments use distinct audiences.\n\nRun `noodle auth doctor src/server.ts` before sharing. Its bounded, read-only probes never register a client.\nAdding the embedded assistant does not choose or rewrite MCP customer auth. Its authenticated backend may\nbind `routing.endpoints.customer_api` during assistant-session exchange from server-owned membership data;\ndirect MCP requests continue to resolve the same endpoint from the configured verified OIDC claim.\n\n## Per-tool authorization remains independent\n\nThe mapped `roles` and `scopes` paths are read only after OIDC verification. The restricted tool declares its\nrule beside the rest of its public contract:\n\n```ts\ntool('list_org_apps', {\n authorization: {\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n },\n // input, output, and fulfilment...\n});\n```\n\nEvery required scope must be present and at least one allowed role must match. When both lists are declared,\nboth conditions apply. Route availability never changes `tools/list`: discovery remains based only on\nroles/scopes. A restricted tool is omitted for an ineligible customer and a guessed direct call still fails\nclosed.\n\nTool code calls the connector normally:\n\n```ts\nfulfil({ input, connectors }) {\n const apps = connectors.app_api.listOrgApps({\n org_id: input.org_id,\n skip: input.skip,\n limit: input.limit,\n });\n\n return { result: apps.result };\n}\n```\n\nThe broker exchanges a short-lived, platform-signed assertion at the fixed token endpoint and caches the\nresult by caller, connector, scopes, and a route fingerprint. The assertion carries only the route key and\nfingerprint, never the URL. The MCP access token is never forwarded to the customer API. The exchange wire\ncontract lives in docs/spec/connectors.md.\n\nFirebase and Microsoft remain supported managed adapters; their provider-specific contracts and tests live\nin docs/spec/auth-and-policy.md and the SharePoint flagship.\n\n## Supabase direct-OIDC access-token hook\n\nDynamic Client Registration lets any OAuth client register, so the presence of `client_id` is not approval.\nKeep an operator-controlled client-to-audience map and rewrite `aud` only for an exact mapped client. For a\ndynamically registered client, review its generated client ID, name, and exact redirect URIs in the consent\nflow before adding the mapping. Each new registration needs its own row; never approve by name or prefix.\n\nReplace `<approved-oauth-client-id>` with the reviewed client ID and `<stable-mcp-audience>` with the exact\nvalue configured in `customerAuth.oidc`:\n\n```sql\ncreate table if not exists public.mcp_oauth_client_audiences (\n client_id text primary key check (btrim(client_id) <> ''),\n audience text not null check (btrim(audience) <> '')\n);\n\nrevoke all on table public.mcp_oauth_client_audiences from authenticated, anon, public;\ngrant usage on schema public to supabase_auth_admin;\ngrant select on table public.mcp_oauth_client_audiences to supabase_auth_admin;\n\ninsert into public.mcp_oauth_client_audiences (client_id, audience)\nvalues ('<approved-oauth-client-id>', '<stable-mcp-audience>')\non conflict (client_id) do update set audience = excluded.audience;\n\ncreate or replace function public.mcp_access_token_hook(event jsonb)\nreturns jsonb\nlanguage plpgsql\nstable\nas $$\ndeclare\n claims jsonb := coalesce(event->'claims', '{}'::jsonb);\n oauth_client_id text := nullif(btrim(claims->>'client_id'), '');\n mapped_audience text;\nbegin\n if oauth_client_id is not null then\n select mapping.audience\n into mapped_audience\n from public.mcp_oauth_client_audiences as mapping\n where mapping.client_id = oauth_client_id;\n end if;\n\n if mapped_audience is not null then\n claims := jsonb_set(\n claims,\n '{aud}',\n to_jsonb(mapped_audience),\n true\n );\n end if;\n\n return jsonb_build_object('claims', claims);\nend;\n$$;\n\ngrant execute on function public.mcp_access_token_hook(jsonb) to supabase_auth_admin;\nrevoke execute on function public.mcp_access_token_hook(jsonb) from authenticated, anon, public;\n```\n\n| Token source | Mapping | Resulting `aud` |\n| --- | --- | --- |\n| Approved OAuth client | Exact client row | Mapped stable MCP audience |\n| Unrelated or unknown OAuth client | No row | Original Supabase audience |\n| Browser session | No `client_id` | Original Supabase audience |\n\nSelect this function under Supabase Auth Hooks before completing the interactive verification below.\n\n## Validate\n\n```bash\nnoodle validate examples/customer-auth/src/server.ts --json\nnoodle auth doctor examples/customer-auth/src/server.ts --json\nnoodle test examples/customer-auth/src/server.ts --json\n```\n\nThe doctor proves metadata and JWKS readiness without registering a client. For this protected app,\n`noodle test` proves the anonymous 401 plus exact protected-resource metadata boundary and reports\n`interactiveRequired: true`; neither command proves token issuance or audience verification.\n\nAgainst a deployed customer-protected environment, set a short-lived real customer token only in\n`NOODLE_CUSTOMER_TOKEN` and add `--live --org <org> --app <app> --env <env>`. The live doctor performs\ncredential exchanges without invoking any business tool. Add `--version 1` when testing a pinned version;\nthe reported customer resource must match that versioned MCP endpoint.\n\n## Run locally\n\n```bash\nnoodle devtools examples/customer-auth/src/server.ts\n```\n\nComplete sign-in in Devtools and load the tool list. That authenticated request is the local proof that DCR,\nPKCE, token issuance, issuer/signature verification, the stable audience, and exact-resource binding work\ntogether. Invoke a representative safe read when the configured customer API is available.\n\n### Test delegated exchange locally\n\nLocal customer OIDC sign-in and delegated-exchange assertion trust are two distinct boundaries. OIDC proves\nthe caller to the local MCP server; Devtools uses a separate local issuer only for the RFC 8693 assertion\nsent to the downstream token endpoint. This is the canonical local path and requires no `server.ts` change,\nflag, environment variable, or config surface.\n\n1. Configure the OIDC authorization server for the exact loopback callback and RFC 8707 resource. Do not add\n the Devtools assertion key to OIDC issuer metadata or change its signing keys.\n2. Start Devtools, complete customer sign-in, and copy the displayed `{ issuer, jwks }` from **Local delegated exchange**.\n3. Pin both values only in the customer-owned development RFC 8693 token endpoint.\n4. Restrict that trust to development client credentials, audience, API, and data.\n5. Invoke the delegated `list_org_apps` tool until its binding reads **Exchange verified**.\n6. Use hosted preview or `noodle auth doctor --live` to prove the production platform issuer.\n\n**Never trust the Devtools issuer in production: anyone holding the local private key could impersonate a customer.**\n\n## Configuration\n\nThe embedded assistant uses a customer-supplied OpenAI Chat Completions-compatible endpoint. Configure its\nmanaged values at the Noodle deployment environment; none of these values belongs in the customer web\napplication environment, and the API key never reaches the browser:\n\nThe assistant session carries a verified user, tenant, deployment, roles, and scopes. For this flagship's\nrouted tools, the embedding backend resolves the signed-in user's cluster from server-owned membership data\nand passes `routing: { endpoints: { customer_api: cluster.apiBaseUrl } }` to\n`createAssistantSession`. Noodle validates and privately stores that route; it is not returned to the\nbrowser. Do not copy the route into page context, session claims, tool input, or model instructions.\n\n```bash\nnoodle variables set ASSISTANT_ORIGIN https://app.example.com --scope env\nnoodle variables set ASSISTANT_MODEL_BASE_URL https://model.example.com/v1 --scope env\nnoodle variables set ASSISTANT_MODEL your-model --scope env\nnoodle secrets set ASSISTANT_MODEL_API_KEY --scope env\nnoodle variables set CUSTOMER_API_CLIENT_ID your-broker-client-id --scope env\nnoodle secrets set CUSTOMER_API_CLIENT_SECRET --scope env\nnoodle check --target embedded-assistant src/server.ts\n```\n\n`ASSISTANT_ORIGIN` is the operator-owned production embedding origin, so one source can serve every customer\nwithout an application fork. Assistant origins are exact. Production embedding origins must use HTTPS; plain HTTP is accepted only for\nloopback development origins such as `http://localhost:3000`, `http://127.0.0.1:3000`, or\n`http://[::1]:3000`. `noodle dev` serves the MCP project, not that separate embedding application.\n\nThe bounded `presentation` object configures the panel, launcher, header, composer, and messages. Its\nprimitives derive colors from shared server `branding`; raw HTML, CSS, inline SVG, renderer classes, and\ncallbacks are not accepted.\n\nCreate the backend credential after deployment. The CLI writes it to a mode-0600 file and never prints the\nsecret:\n\n```bash\nnoodle assistant clients create --name web --org noodleseed --app customer-auth --env prod\n```\n\nOnly the Noodle service URL, assistant client ID, and assistant client secret belong in the authenticated\ncustomer backend. The model URL, model name, and model API key remain managed by the Noodle deployment.\n\nThe customer's authenticated backend calls `createAssistantSession(...)` from\n`@noodleseed/assistant/server`, passing the already-verified user and browser origin. The browser then uses\nthe returned short-lived session through the managed Web Component/React renderer or a customer-owned UI:\n\n```bash\npnpm add @noodleseed/assistant\n```\n\n```tsx\nimport { NoodleAssistant } from '@noodleseed/assistant/react';\n\n<NoodleAssistant\n sessionEndpoint=\"/api/noodle-assistant/session\"\n theme={resolvedTheme}\n onSessionExpired={() => console.info('Assistant session renewed')}\n/>;\n```\n\n`resolvedTheme` is the application's current `'light' | 'dark'` value. Use `theme=\"auto\"` only when the\nbrowser operating-system preference is intentionally authoritative.\n\nFor an entirely application-owned React renderer, use the renderer-free hook. It creates no custom element\nand returns the AI SDK transcript plus the canonical client commands:\n\n```tsx\n'use client';\n\nimport { useEffect, useState } from 'react';\nimport { NoodleAppView } from '@noodleseed/assistant/react';\nimport { useNoodleAssistant } from '@noodleseed/assistant/react/client';\n\nexport function CustomerAssistant({\n principalKey,\n resolvedTheme,\n}: {\n principalKey: string;\n resolvedTheme: 'light' | 'dark';\n}) {\n const [draft, setDraft] = useState('');\n const { client, messages, status, error } = useNoodleAssistant({\n sessionEndpoint: '/api/noodle-assistant/session',\n principalKey,\n });\n const busy = status === 'submitted' || status === 'streaming';\n const settle = (operation: Promise<void>) => {\n void operation.catch(() => {\n // The hook exposes this same structured failure through `error`.\n });\n };\n\n return (\n <section aria-label=\"Assistant\" aria-busy={busy}>\n {messages.map((message) => (\n <article key={message.id} data-role={message.role}>\n {message.parts.map((part, index) => {\n if (part.type === 'text') return <p key={index}>{part.text}</p>;\n if (part.type === 'data-confirmation') {\n const review = part.data;\n return (\n <section key={review.id} aria-label=\"Review proposed action\">\n <h3>{review.title ?? 'Review proposed action'}</h3>\n {review.description ? <p>{review.description}</p> : null}\n <pre aria-label=\"Proposed action arguments\">\n {JSON.stringify(review.arguments ?? {}, null, 2)}\n </pre>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'accept' }))}\n >\n Confirm\n </button>\n <button\n disabled={busy || review.status !== 'pending'}\n onClick={() => settle(client.respond(review.id, { action: 'decline' }))}\n >\n Don't proceed\n </button>\n </section>\n );\n }\n if (part.type === 'data-input-request') {\n const request = part.data;\n return (\n <section key={request.id} aria-label=\"Assistant needs input\">\n <p>{request.message}</p>\n <p>This renderer has not implemented the requested form.</p>\n <button\n disabled={busy || request.status !== 'pending'}\n onClick={() => settle(client.respond(request.id, { action: 'decline' }))}\n >\n Cancel request\n </button>\n </section>\n );\n }\n if (part.type === 'data-tool-result') {\n return (\n <pre key={part.data.id} aria-label={`${part.data.tool} result`}>\n {JSON.stringify(part.data.result, null, 2)}\n </pre>\n );\n }\n if (part.type === 'data-view') {\n return (\n <NoodleAppView\n key={`${part.data.id}:${part.data.resourceUri}`}\n client={client}\n view={part.data}\n theme={resolvedTheme}\n />\n );\n }\n return <p key={index}>Unsupported assistant content.</p>;\n })}\n </article>\n ))}\n {error ? <p role=\"alert\">{error.message}</p> : null}\n <form\n onSubmit={(event) => {\n event.preventDefault();\n const message = draft.trim();\n if (!message) return;\n setDraft('');\n settle(client.sendMessage(message));\n }}\n >\n <input\n aria-label=\"Message\"\n value={draft}\n onChange={(event) => setDraft(event.currentTarget.value)}\n />\n {busy ? (\n <button type=\"button\" onClick={() => client.abort()}>\n Stop\n </button>\n ) : (\n <button type=\"submit\">Send</button>\n )}\n </form>\n </section>\n );\n}\n```\n\n`principalKey` stays in the browser. Change it whenever the authenticated user or tenant changes; the hook\nthen aborts and clears the prior session and transcript. The sample fails closed on input requests until its\nfallback is replaced with a form generated from `requestedSchema`. A production renderer must show the\ncomplete confirmation review and both decisions. For `data-view`, map `resourceUri` or `tool` and the\nbounded/redacted result to a component already trusted by this application only when intentionally replacing\nthe linked App with a native UI. Otherwise use `<noodle-app-view>` or its React `NoodleAppView` adapter;\nJSON result data is not the App UI. The element's semantic lifecycle identity is the client plus `view.id`\nplus `view.resourceUri`, so parent payload/callback rerenders keep the iframe and only a different view,\ndisconnect, or App teardown request retires the bridge.\nApp views remain inline by default: the host advertises only inline presentation and rejects a widget's\nfullscreen request. A customer-owned renderer may opt in explicitly with `allowFullscreen` on\n`NoodleAppView` or `allow-fullscreen` on `<noodle-app-view>` only when fullscreen is part of its intended\nexperience. When fullscreen is accepted, the shared host adds a top-right exit control that returns the same\nmounted App to inline mode without discarding its state.\nNever inject `part.data.html`, assign it to `srcdoc`, fetch a `ui://` URI, or reproduce the bridge directly. Pages with a\nContent-Security-Policy must include the Noodle service origin in both `connect-src` and `frame-src`.\n\nBefore the production-equivalent host build, run the presence-only handoff check:\n\n```sh\nnoodle assistant embed --check --json\n```\n\nAdd application-owned delegated-exchange requirements with repeatable `--require-env NAME` flags. The JSON\nreports required and missing names, CSP status, and post-deploy probes without returning environment values\nor writing scaffold files. Map the names through the production secret manager, CI environment, and any\nsecret allowlist; regenerate existing framework-owned environment binding types before the build. Default\nDevtools/model exercises to synthetic data, and obtain approval before sending real connector data to an\nexternal model.\n\nAfter deployment, use the assistant doctor to verify the embed client, model, and static session boundary:\n\n```sh\nnoodle assistant doctor --user-id <real-test-user> --origin \"$PUBLIC_APP_ORIGIN\" --org <org> --app <app> --env <env>\n```\n\nThe doctor does not invent or test an application-specific customer route. Prove routed assistant tools by\nhaving the authenticated embedding backend pass the user's server-verified endpoint during session\nexchange, then invoke one representative safe read.\n\nIf the application deliberately sends a first turn on mount, do not combine a persistent \"sent\" ref with a\nmount effect. React Strict Mode can abort that provisional request and then suppress the stable remount.\nSchedule the send after the provisional cleanup and settle its promise:\n\n```tsx\nuseEffect(() => {\n let active = true;\n queueMicrotask(() => {\n if (active) settle(client.sendMessage(initialMessage));\n });\n return () => {\n active = false;\n };\n}, [client, initialMessage]);\n```\n\nFor a chat-first custom host, raw `tool_started` supplies the direct call `id` and technical tool name. Map\nknown tools to concise application copy and use a neutral fallback. Reserve a stable `role=\"status\"` region\nfor thinking, tool activity, and the view skeleton; switch to the ready `<noodle-app-view>` (or React\n`NoodleAppView`) on `view_available` or to `role=\"alert\"` on error. Decorative skeleton shapes stay hidden from assistive technology, and shimmer\nor transition motion is disabled under `prefers-reduced-motion`.\n\nUse `${view.id}:${view.resourceUri}` as transport identity. Different call IDs are distinct invocations and\nmust not be deduplicated generically. If this application intentionally owns one current panel for a known\nresource, declare an application-owned slot for that resource and replace only that slot.\n\nOutside React, subscribe to the DOM-free client directly and use the isolated framework-neutral App host.\nIt exposes the same conversation as headless AI SDK `UIMessage` state, including typed confirmation, input,\ntool-result, and linked-view parts, without installing React:\n\n```html\n<noodle-app-view id=\"assistant-app-view\"></noodle-app-view>\n```\n\n```ts\nimport '@noodleseed/assistant/app-view';\nimport { createAssistantClient } from '@noodleseed/assistant/client';\n\nconst assistant = createAssistantClient({\n sessionEndpoint: '/api/noodle-assistant/session',\n});\nconst appView = document.querySelector('#assistant-app-view');\nif (!appView) throw new Error('Missing App view host');\nappView.client = assistant;\nappView.theme = resolvedTheme;\n\nassistant.subscribeChat((state) => {\n renderUIMessageState(state);\n for (const message of state.messages) {\n for (const part of message.parts) {\n if (part.type === 'data-confirmation' && part.data.status === 'pending') {\n renderConfirmation(part.data, (response) => assistant.respond(part.data.id, response));\n }\n if (part.type === 'data-view') appView.view = part.data;\n }\n }\n});\n```\n\n`theme=\"auto\"` follows the operating-system preference, not a SaaS-owned toggle. Pass the resolved\n`light`/`dark` theme to `NoodleAssistant` and `<noodle-app-view>`/`NoodleAppView`; updates reach mounted MCP Apps without a\nremount. CSS custom properties inherit through the host, and documented `--ns-assistant-*` variables remain\nthe final integration escape hatch. Server `branding` is shared by widgets and the assistant; there is no\nsecond branding declaration. Text streams progressively. Expired turns re-exchange and retry once;\nconfirmations never replay automatically.\n\nThe customer IdP must place the full tenant API base URL in `tenant.api_base_url`. For example, one verified\ncustomer may receive `https://customer-a.api.noodleseed.dev/v1` and another\n`https://customer-b.api.noodleseed.dev/v1`; both satisfy the declared suffix policy. Application code,\ndeployment variables, and connector arguments do not select the tenant route.\n\n`CUSTOMER_API_CLIENT_ID` and `CUSTOMER_API_CLIENT_SECRET` authenticate only the broker to the fixed exchange\nendpoint. They are not customer API bearer tokens. The exchange endpoint verifies the platform-signed\nsubject assertion and mints a short-lived token scoped to the signed-in user and route binding.\n\n## Deploy customer-protected to Noodle Seed Cloud\n\n```bash\nnoodle deploy examples/customer-auth/src/server.ts \\\n --org noodleseed \\\n --app customer-auth \\\n --env prod \\\n --access customers\n```\n\nEndpoint:\n\n```text\nhttps://cloud.noodleseed.dev/o/noodleseed/customer-auth/mcp\n```\n\n## MCP Primitives\n\n- Tool `list_my_organizations`: calls `GET /api/organizations` and returns the organizations the signed-in\n customer is a member of. Takes no arguments; the org set is scoped by the verified customer session.\n- Tool `list_org_apps`: calls `GET /api/organizations/{org_id}/apps` for one organization `org_id`.\n- Tool `archive_org_app`: after confirmation, calls\n `POST /api/organizations/{org_id}/apps/{app_id}/archive`.\n\n## Auth boundary\n\nNoodle Seed verifies the configured OIDC issuer and stable audience, then binds the exact transport-derived\nMCP resource before reading identity or routing claims. Public caller identity contains the user/role/scope\nprojection; the customer route remains private request state.\n\nConnector-backed tools ask the broker for a route-bound delegated credential; only the endpoint key and\nfingerprint enter broker cache/single-flight state or the assertion. The route claim and inbound MCP bearer\ntoken never reach tools, connectors, widgets, model output, or downstream systems. Confirmed actions keep\nthe same URL-blind binding only in private continuation state and reject acceptance-time drift.\n" },
56
56
  { relPath: "examples/customer-auth/noodle.json", content: "{\n \"entrypoint\": \"src/server.ts\",\n \"name\": \"customer-auth\"\n}\n" },
57
57
  { relPath: "examples/customer-auth/package.json", content: "{\n \"name\": \"customer-auth\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"test\": \"vitest run\",\n \"validate\": \"noodle validate\",\n \"dev\": \"noodle dev\",\n \"deploy\": \"noodle deploy\"\n },\n \"devDependencies\": {\n \"@noodleseed/one\": \"latest\",\n \"vitest\": \"latest\"\n }\n}\n" },
58
58
  { relPath: "examples/customer-auth/src/server.ts", content: "import {\n annotations,\n authenticatedWebsite,\n connector,\n customerAuth,\n customerEndpoint,\n embeddedAssistant,\n openAICompatible,\n secret,\n server,\n tool,\n variable,\n z,\n} from '@noodleseed/one';\n\nconst customerApi = customerEndpoint('customer_api', {\n allowedHttpsHostSuffixes: ['api.noodleseed.dev'],\n});\nconst assistantOrigin = variable('ASSISTANT_ORIGIN');\n\nconst noodleseedApi = connector('noodleseed_app_api')\n .version('1.0.0')\n .http({\n baseUrl: customerApi,\n auth: {\n kind: 'delegatedTokenExchange',\n tokenUrl: 'https://id.noodleseed.dev/oauth/token',\n clientId: variable('CUSTOMER_API_CLIENT_ID'),\n clientSecret: secret('CUSTOMER_API_CLIENT_SECRET'),\n scopes: ['organizations:read', 'org_apps:read', 'org_apps:write'],\n audience: 'noodleseed-customer-api',\n },\n operations: {\n list_org_apps: {\n type: 'read',\n method: 'GET',\n path: '/api/organizations/${args.org_id}/apps',\n query: ['skip', 'limit'],\n input: z.object({\n org_id: z.string(),\n skip: z.number().optional(),\n limit: z.number().optional(),\n }),\n output: z.object({ result: z.unknown().optional() }),\n response: {\n result: '${response}',\n },\n },\n list_organizations: {\n type: 'read',\n method: 'GET',\n path: '/api/organizations',\n output: z.object({ organizations: z.array(z.unknown()).optional() }),\n response: {\n organizations: '${response.organizations}',\n },\n },\n archive_org_app: {\n type: 'action',\n method: 'POST',\n path: '/api/organizations/${args.org_id}/apps/${args.app_id}/archive',\n input: z.object({\n org_id: z.string(),\n app_id: z.string(),\n }),\n output: z.object({ archived: z.boolean() }),\n response: {\n archived: '${response.archived}',\n },\n },\n },\n });\n\nconst CUSTOMER_AUTH_AGENT_GUIDE = {\n description:\n 'Use the signed-in customer context to discover organizations, review their Noodle Seed apps, and archive a selected app when authorized.',\n useWhen: [\n 'A signed-in customer asks which organizations or apps they can access.',\n 'An organization administrator asks to archive one selected app.',\n ],\n workflows: [\n {\n id: 'find_organizations',\n title: 'Find the customer organizations',\n intent: 'Ground later organization-scoped work in the verified customer membership.',\n steps: [\n {\n capability: { kind: 'tool', name: 'list_my_organizations' },\n guidance: 'Use an organization identifier returned by this read in later steps.',\n },\n ],\n },\n {\n id: 'review_organization_apps',\n title: 'Review apps in one organization',\n steps: [\n { capability: { kind: 'tool', name: 'list_my_organizations' } },\n {\n capability: { kind: 'tool', name: 'list_org_apps' },\n guidance: 'List apps only for an organization returned for the signed-in customer.',\n },\n ],\n },\n {\n id: 'archive_organization_app',\n title: 'Archive one organization app',\n steps: [\n { capability: { kind: 'tool', name: 'list_my_organizations' } },\n { capability: { kind: 'tool', name: 'list_org_apps' } },\n {\n capability: { kind: 'tool', name: 'archive_org_app' },\n guidance: 'Archive only the exact app the customer selected after confirmation.',\n },\n ],\n },\n ],\n boundaries: [\n 'Never infer an organization or app identifier that was not returned for the signed-in customer.',\n 'Never claim an app was archived until the confirmed action succeeds.',\n ],\n examples: [\n { prompt: 'Which organizations can I access?', workflow: 'find_organizations' },\n { prompt: 'Show me the apps in this organization.', workflow: 'review_organization_apps' },\n { prompt: 'Archive the app I selected.', workflow: 'archive_organization_app' },\n ],\n} as const;\n\nexport default server(\n 'noodleseed_customer_auth',\n {\n title: 'NoodleSeed.com Customer Auth',\n version: '1.0.0',\n branding: {\n name: 'Noodle Seed Assistant',\n accent: '#E85D24',\n surface: '#FFFFFF',\n surfaceDark: '#171310',\n colorScheme: 'auto',\n theme: {\n light: { accentText: '#FFFFFF', text: '#1C1714' },\n dark: { accent: '#FF8A4C', accentText: '#1C100A', text: '#FFF8F2' },\n },\n },\n use: { app_api: noodleseedApi },\n agentGuide: CUSTOMER_AUTH_AGENT_GUIDE,\n interactions: { confirmationFallback: 'host' },\n auth: customerAuth.oidc({\n issuer: 'https://id.noodleseed.dev',\n audience: 'noodleseed-customer-auth-prod',\n claims: {\n id: 'sub',\n email: 'email',\n name: 'name',\n orgs: 'permissions.orgs',\n roles: 'permissions.roles',\n scopes: 'permissions.scopes',\n },\n routing: {\n endpoints: {\n customer_api: { claim: 'tenant.api_base_url' },\n },\n },\n }),\n instructions:\n 'Direct/federated MCP OIDC demo. The customer IdP proves identity and privately selects the tenant API base URL, while the broker supplies delegated credentials and confirmed actions stay bound to the reviewed route.',\n assistant: embeddedAssistant({\n model: openAICompatible({\n baseUrl: variable('ASSISTANT_MODEL_BASE_URL'),\n model: variable('ASSISTANT_MODEL'),\n apiKey: secret('ASSISTANT_MODEL_API_KEY'),\n }),\n // Production origins are exact HTTPS; http://localhost:<port> is allowed for local development.\n access: authenticatedWebsite({\n origins: [assistantOrigin, 'https://dev.noodleseed.com', 'http://localhost:3000'],\n }),\n layout: { mode: 'floating', position: 'bottom-right', panelWidth: 420 },\n labels: {\n welcomeHeading: 'How can I help with Noodle Seed?',\n composerPlaceholder: 'Ask about your apps…',\n },\n presentation: {\n panel: { surface: 'glass', elevation: 'soft', border: 'subtle' },\n launcher: { icon: 'brand-mark', status: 'session', effect: 'pulse' },\n header: {\n mark: 'status',\n badge: { text: 'Workspace online', tone: 'success', indicator: true },\n },\n composer: { leadingIcon: 'brand-mark', shape: 'pill' },\n },\n suggestedPrompts: ['Explain how to connect this customer-authenticated MCP server'],\n }),\n },\n [\n tool('list_org_apps', {\n title: 'List organization apps',\n description: 'List NoodleSeed.com apps for an organization from its customer API.',\n authorization: {\n requiredScopes: ['org_apps:read'],\n allowedRoles: ['org_admin', 'org_member'],\n },\n input: z.object({\n org_id: z.string().meta({ title: 'Organization' }),\n skip: z.number().int().min(0).optional().meta({ title: 'Starting item' }),\n limit: z.number().int().min(1).max(100).optional().meta({ title: 'Maximum results' }),\n }),\n output: z.object({\n result: z.unknown(),\n }),\n annotations: annotations.readOnly(),\n fulfil({ input, connectors }) {\n const apps = connectors.app_api.listOrgApps({\n org_id: input.org_id,\n skip: input.skip,\n limit: input.limit,\n });\n return {\n result: apps.result,\n };\n },\n }),\n tool('list_my_organizations', {\n title: 'List my organizations',\n description: 'List the NoodleSeed.com organizations the signed-in customer belongs to.',\n contextProvider: true,\n input: z.object({}),\n // The customer API returns every organization for the signed-in customer in one response, with no\n // page parameter to pass through, so the bound is declared on the shape. A customer belongs to a\n // handful of organizations; `noodle check` reports an unbounded list as\n // `tool_design_output_bounds`.\n output: z.object({\n organizations: z.array(z.unknown()).max(100),\n }),\n annotations: annotations.readOnly(),\n fulfil({ connectors }) {\n const organizations = connectors.app_api.listOrganizations();\n return {\n organizations: organizations.organizations,\n };\n },\n }),\n tool('archive_org_app', {\n title: 'Archive organization app',\n description: 'Archive one NoodleSeed.com app through its customer API after confirmation.',\n authorization: {\n requiredScopes: ['org_apps:write'],\n allowedRoles: ['org_admin'],\n },\n input: z.object({\n org_id: z.string().meta({ title: 'Organization' }),\n app_id: z.string().meta({ title: 'App' }),\n }),\n output: z.object({\n archived: z.boolean(),\n }),\n annotations: annotations.openAction({ destructive: false, confirm: true }),\n fulfil({ input, connectors }) {\n const result = connectors.app_api.archiveOrgApp({\n org_id: input.org_id,\n app_id: input.app_id,\n });\n return {\n archived: result.archived,\n };\n },\n }),\n ],\n);\n" },
@@ -516,14 +516,19 @@ export function renderEmbeddedAssistantReference() {
516
516
  '',
517
517
  '`settle` must await or catch the command promise; the same structured failure also appears in the hook `error` state.',
518
518
  '',
519
- 'The sample fails closed on input requests until you replace that branch with a form generated from `requestedSchema`. A custom renderer must show the complete confirmation review and both decisions, handle every part it supports, and surface an explicit unsupported state for the rest. For `data-view`, use `NoodleAppView` to render the linked App or deliberately map `resourceUri`/tool plus the bounded redacted `result` to an application-trusted native component. JSON result data is not the linked App UI. Never inject `part.data.html`, assign it to `srcdoc`, fetch a `ui://` URI, or reproduce the bridge with a direct Ext Apps dependency. Do not wrap this client in another chat transport or invent user messages for interaction continuations.',
519
+ 'The sample fails closed on input requests until you replace that branch with a form generated from `requestedSchema`. A custom renderer must show the complete confirmation review and both decisions, handle every part it supports, and surface an explicit unsupported state for the rest. For `data-view`, use the canonical `<noodle-app-view>` host (or its React `NoodleAppView` adapter) to render the linked App, or deliberately map `resourceUri`/tool plus the bounded redacted `result` to an application-trusted native component. JSON result data is not the linked App UI. Never inject `part.data.html`, assign it to `srcdoc`, fetch a `ui://` URI, or reproduce the bridge with a direct Ext Apps dependency. Do not wrap this client in another chat transport or invent user messages for interaction continuations.',
520
520
  '',
521
- '`NoodleAppView` owns one bridge for the semantic view identity: client + `view.id` + `view.resourceUri`. It retains the iframe across fresh payload/callback/theme rerenders, reads current payloads through refs, publishes later resolved-theme changes through MCP Apps host context, and sends standard App teardown only when that semantic identity changes or the component unmounts. Pass the same resolved application theme used by the conversation shell. Do not key an ancestor by a view object or callback. If the embedding page sets Content-Security-Policy, include the Noodle service origin in both `connect-src` and `frame-src`.',
521
+ '`<noodle-app-view>` owns one bridge for the semantic view identity: client + `view.id` + `view.resourceUri`; `NoodleAppView` delegates to it. The host retains the iframe across fresh payload/callback/theme rerenders, publishes later resolved-theme changes through MCP Apps host context, and sends standard App teardown when that semantic identity changes, the element disconnects, or the App requests teardown. App views remain inline by default; the host advertises only inline presentation and rejects widget fullscreen requests. Opt in with `allowFullscreen` on `NoodleAppView` or `allow-fullscreen` on `<noodle-app-view>` only when fullscreen is an intentional part of the customer-owned experience. When fullscreen is accepted, the shared host adds an accessible top-right exit control that returns the same mounted App to inline mode without losing its state. Pass the same resolved application theme used by the conversation shell. Do not key an ancestor by a view object or callback. If the embedding page sets Content-Security-Policy, include the Noodle service origin in both `connect-src` and `frame-src`.',
522
522
  '',
523
- 'Outside React, use the same DOM-free client directly. It keeps the session token in memory, exposes a React-free `UIMessage` transcript with typed parts, and never registers a custom element:',
523
+ 'Outside React, use the same DOM-free client directly and import the isolated App-view entry only when rendering linked Apps. The client keeps the session token in memory, the transcript stays React-free, and the element owns only App presentation:',
524
+ '',
525
+ '```html',
526
+ '<noodle-app-view id="assistant-app-view"></noodle-app-view>',
527
+ '```',
524
528
  '',
525
529
  '```ts',
526
530
  'import { createAssistantClient } from "@noodleseed/assistant/client";',
531
+ 'import "@noodleseed/assistant/app-view";',
527
532
  '',
528
533
  'const assistant = createAssistantClient({',
529
534
  ' sessionEndpoint: "/api/assistant/session",',
@@ -533,6 +538,11 @@ export function renderEmbeddedAssistantReference() {
533
538
  ' }),',
534
539
  '});',
535
540
  '',
541
+ 'const appView = document.querySelector("#assistant-app-view");',
542
+ 'if (!appView) throw new Error("Missing App view host");',
543
+ 'appView.client = assistant;',
544
+ "appView.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';",
545
+ '',
536
546
  'assistant.updateModelContext({',
537
547
  " content: [{ type: 'text', text: 'The time-off form is mounted.' }],",
538
548
  " structuredContent: { widget: { name: 'time-off', lifecycle: 'mounted' } },",
@@ -551,7 +561,7 @@ export function renderEmbeddedAssistantReference() {
551
561
  ' pending = { id: part.data.id, requestedSchema: part.data.requestedSchema };',
552
562
  ' }',
553
563
  " if (part.type === 'data-view') {",
554
- ' renderRegisteredView(part.data.resourceUri, part.data.result);',
564
+ ' appView.view = part.data;',
555
565
  ' }',
556
566
  ' }',
557
567
  ' }',
@@ -590,7 +600,7 @@ export function renderEmbeddedAssistantReference() {
590
600
  '});',
591
601
  '```',
592
602
  '',
593
- '`data-view` means a completed tool has a linked MCP App view. In a customer-owned React renderer, pass that typed part and the existing client to `NoodleAppView`; it retains one bridge for client + `view.id` + `view.resourceUri` and requests standard App teardown on semantic replacement or unmount. That pair is transport identity: different call ids are distinct invocations and must not be deduplicated generically. If the product intentionally owns one current panel for a known resource, declare an application-owned slot map and replace only that slot. Deliberately map the bounded result to an application-trusted native component only when replacing the linked App UI.',
603
+ '`data-view` means a completed tool has a linked MCP App view. Pass that typed part and the existing client to `<noodle-app-view>` in Vue, Angular, or plain DOM, or to its `NoodleAppView` React adapter. It retains one bridge for client + `view.id` + `view.resourceUri` and requests standard App teardown on semantic replacement, disconnect, or App request. That pair is transport identity: different call ids are distinct invocations and must not be deduplicated generically. If the product intentionally owns one current panel for a known resource, declare an application-owned slot map and replace only that slot. Deliberately map the bounded result to an application-trusted native component only when replacing the linked App UI.',
594
604
  '',
595
605
  '`clientContext` and typed `pageContext` are recomputed for each turn. `updateContext(...)` remains the legacy session-exchange context; `updatePageContext(...)` replaces the fresh per-turn application hint. `updateModelContext({ content, structuredContent })` publishes one cohesive renderer snapshot for later message turns without starting a turn; every call replaces the prior snapshot rather than merging fields. These are untrusted data, not conversation history or authorization input, and the boundaries reject credential-shaped or unbounded updates. A message may re-exchange once after a pre-execution `401`; the client never auto-retries interaction decisions. `tool_proposed.arguments` is a complete schema-aware review projection and, for connector-backed tools, names the sole exact connector version/operation/resolved arguments. Sensitive/write-only fields are redacted; truncating or omitting any non-sensitive action field fails closed. Accept is bound to the server-held action and claims at most one execution attempt—clients cannot replace it. Normal terminal outcomes scrub private arguments and continuations immediately; only an accepted action still executing retains them for the one-hour unknown-outcome recovery window, after which it records `interaction_outcome_unknown` and scrubs. Without downstream idempotency this is not an exactly-once business-effect guarantee. To reconcile a lost response, explicitly repeat the same id and decision: the service returns its durable stored outcome without re-execution.',
596
606
  '',
@@ -615,7 +625,7 @@ export function renderEmbeddedAssistantReference() {
615
625
  '',
616
626
  '- Node.js 20+ for `@noodleseed/assistant/server`.',
617
627
  '- The package ships ESM and CommonJS with full export conditions; no bundler aliases, `transpilePackages`, or ambient type shims are needed. If resolution fails, the installed package version is outdated: update `@noodleseed/assistant` instead of adding workarounds.',
618
- '- TypeScript `moduleResolution` `bundler` or `node16` recommended; classic `node` also resolves the `/client`, `/react`, `/react/client`, and `/server` subpaths.',
628
+ '- TypeScript `moduleResolution` `bundler` or `node16` recommended; classic `node` also resolves the `/app-view`, `/client`, `/react`, `/react/client`, and `/server` subpaths.',
619
629
  '',
620
630
  '## Verify the boundary',
621
631
  '',
@@ -2,8 +2,9 @@
2
2
 
3
3
  Customer-branded embedded assistant surfaces for Noodle Seed deployments.
4
4
 
5
- The package exports the canonical `<noodle-assistant>` Web Component, a managed React wrapper and secure
6
- `NoodleAppView` MCP App renderer from `@noodleseed/assistant/react`, a renderer-free React hook from
5
+ The package exports the canonical `<noodle-assistant>` managed Web Component, the framework-neutral
6
+ `<noodle-app-view>` MCP App host from `@noodleseed/assistant/app-view`, a managed React wrapper and
7
+ `NoodleAppView` adapter from `@noodleseed/assistant/react`, a renderer-free React hook from
7
8
  `@noodleseed/assistant/react/client`, a DOM-free client from `@noodleseed/assistant/client`, and the
8
9
  backend-only `createAssistantSession` helper from `@noodleseed/assistant/server`. Light, dark, and automatic
9
10
  themes work without configuration; the component inherits the deployed MCP server's brand kit while slots,
@@ -376,20 +377,54 @@ if (part.type === "data-view") {
376
377
  }
377
378
  ```
378
379
 
379
- `NoodleAppView` owns the double iframe and AppBridge. Its lifecycle identity is the supplied client plus
380
+ `<noodle-app-view>` owns the double iframe and AppBridge; `NoodleAppView` delegates to it. Its lifecycle identity is the supplied client plus
380
381
  `view.id` plus `view.resourceUri`: ordinary parent rerenders and fresh view/callback objects retain the
381
382
  iframe, while a semantic view replacement or unmount requests standard App teardown and closes the bridge.
382
383
  Do not also key an ancestor by the whole view object or a callback. Pass the embedding application's
383
384
  resolved `"light"` or `"dark"` theme; later changes are published through MCP Apps host context without
384
385
  replacing the iframe.
385
386
 
387
+ App views stay inline by default. The host advertises only inline presentation and rejects an untrusted
388
+ App's fullscreen request, so stale or third-party widget code cannot take over the embedding application's
389
+ viewport. If fullscreen is an intentional part of the customer-owned experience, opt in explicitly with
390
+ `allowFullscreen` on `NoodleAppView` or `allow-fullscreen` on `<noodle-app-view>`; do not enable it merely
391
+ because a widget requests it. After an accepted fullscreen request, the host displays an accessible exit
392
+ control in the top-right corner. It returns the same mounted App to inline mode without resetting its state.
393
+
394
+ Vue, Angular, and plain DOM renderers use the same host without installing React. Import its dedicated entry
395
+ once, then assign the complex values as element properties. In Vue, the explicit `.prop` modifier makes that
396
+ boundary unambiguous:
397
+
398
+ ```vue
399
+ <script setup lang="ts">
400
+ import "@noodleseed/assistant/app-view";
401
+ </script>
402
+
403
+ <template>
404
+ <noodle-app-view
405
+ :client.prop="assistant"
406
+ :view.prop="part.data"
407
+ :theme="resolvedTheme"
408
+ @assistant-error="reportAssistantError"
409
+ />
410
+ </template>
411
+ ```
412
+
413
+ Configure Vue's `isCustomElement` for `noodle-app-view`. Angular uses the same element with `[client]`,
414
+ `[view]`, and `[theme]` property bindings. Do not serialize `client` or `view` into attributes.
415
+
416
+ `<noodle-app-view>` is the canonical host; `NoodleAppView` delegates to it. Both use the
417
+ service-advertised sandbox URL, route App calls through the supplied client, publish theme changes without
418
+ replacing the iframe, and request standard teardown on semantic replacement, disconnect, or an App teardown
419
+ request.
420
+
386
421
  The App document owns its action intent: it calls standard `tools/call` after connecting and never relies on
387
422
  native form navigation. If that call needs input or confirmation, the same `client` publishes the normal
388
423
  pending interaction part for either managed or customer-owned rendering. The original App call stays pending
389
424
  and receives its MCP result after `client.respond(...)`; applications must not retry or translate the click.
390
425
 
391
- Outside React, subscribe to the DOM-free AI SDK `UIMessage` state without registering a custom element or
392
- touching browser storage:
426
+ Outside React, subscribe to the DOM-free AI SDK `UIMessage` state without touching browser storage. The
427
+ client itself registers no element; import `/app-view` only when the transcript renders linked MCP Apps:
393
428
 
394
429
  ```ts
395
430
  import { createAssistantClient } from "@noodleseed/assistant/client";
@@ -491,8 +526,8 @@ flow collects all elicited input before its first connector operation.
491
526
 
492
527
  A completed widget-linked tool emits typed `view_available` data with its call/interaction id, tool,
493
528
  `ui://` resource identity, optional title, bounded/redacted public result, and—on current services—the
494
- self-contained App document. This is an availability signal, not proof of rendering. A customer-owned React
495
- renderer either mounts the actual App with `NoodleAppView` or deliberately substitutes a component already
529
+ self-contained App document. This is an availability signal, not proof of rendering. A customer-owned
530
+ renderer either mounts the actual App with `<noodle-app-view>` (or its React `NoodleAppView` adapter) or deliberately substitutes a component already
496
531
  trusted by the application and selected by `resourceUri`/tool. The JSON `result` is data for a native
497
532
  component; serializing it is not a rendering of the linked App. Never fetch the `ui://` URI, inject
498
533
  `part.data.html`, or assign it to `srcdoc` yourself. The standard element also forwards the same detail as a
@@ -615,7 +650,7 @@ shadow-DOM selectors and classes are not public API.
615
650
 
616
651
  `theme="auto"` follows the browser's operating-system color preference. When the embedding application has
617
652
  its own theme toggle, pass its resolved `"light"` or `"dark"` value to `NoodleAssistant` and every
618
- `NoodleAppView`. Updates change the assistant in place and notify mounted MCP Apps through standard host
653
+ `<noodle-app-view>`/`NoodleAppView`. Updates change the assistant in place and notify mounted MCP Apps through standard host
619
654
  context.
620
655
 
621
656
  Server branding controls customer name, themed logo/mark/avatar assets, semantic light/dark colors, density,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@noodleseed/assistant",
3
3
  "version": "1.22.0",
4
- "description": "Embed the Noodle Seed customer-branded assistant in your web app with a Web Component, managed or custom React UI, DOM-free client, and backend session helper. Authoring and deploying the server is @noodleseed/one.",
4
+ "description": "Embed the Noodle Seed customer-branded assistant in your web app with managed or framework-owned UI, a framework-neutral MCP App host, a DOM-free client, and a backend session helper. Authoring and deploying the server is @noodleseed/one.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -26,6 +26,17 @@
26
26
  },
27
27
  "default": "./dist/index.js"
28
28
  },
29
+ "./app-view": {
30
+ "import": {
31
+ "types": "./dist/app-view.d.ts",
32
+ "default": "./dist/app-view.js"
33
+ },
34
+ "require": {
35
+ "types": "./dist/app-view.d.cts",
36
+ "default": "./dist/app-view.cjs"
37
+ },
38
+ "default": "./dist/app-view.js"
39
+ },
29
40
  "./client": {
30
41
  "import": {
31
42
  "types": "./dist/client.d.ts",
@@ -103,6 +114,9 @@
103
114
  "module": "./dist/index.js",
104
115
  "typesVersions": {
105
116
  "*": {
117
+ "app-view": [
118
+ "./dist/app-view.d.ts"
119
+ ],
106
120
  "react": [
107
121
  "./dist/react.d.ts"
108
122
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noodleseed/one",
3
- "version": "0.136.0",
3
+ "version": "0.137.0",
4
4
  "private": false,
5
5
  "description": "Noodle CLI by Noodle Seed — author, run, and deploy declarative MCP servers. Embedding the assistant in your own web app is @noodleseed/assistant.",
6
6
  "license": "Apache-2.0",