Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ npm run typecheck && npm test # 252 server-side tests + 33 web tests
npm run e2e # 17 real-browser tests (Playwright), incl. the two-approver flow and accessibility scans of every page
```

**Visual card (MCP Apps):** tools return a `ui://` card hosts can render on screens (verdict, red flags, "Alexa cannot approve this"); voice-only clients still get full text.

**Connecting to Alexa+:** [docs/alexa-integration.md](docs/alexa-integration.md) says what is real (MCP server, OAuth 2.1 + PKCE account linking) and what is simulated (the Alexa+ voice assistant), and lists the steps to connect.

**Safe rule changes:** `npm run backtest -- --candidate rules-2026.10.4 --baseline rules-2026.10.3` replays every stored check under two rule sets and lists who got stricter or looser, before anything goes live.
Expand Down
4 changes: 1 addition & 3 deletions apps/mcp-server/package.json
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
{ "name": "@second-opinion/mcp-server", "version": "0.1.0", "private": true, "type": "module",
"dependencies": { "@second-opinion/shared": "*", "@second-opinion/engine": "*", "@second-opinion/store": "*", "@second-opinion/policy": "*", "@second-opinion/notify": "*",
"@modelcontextprotocol/sdk": "1.32.1", "express": "^5.2.1", "zod": "^4.0.0" } }
{"name":"@second-opinion/mcp-server","version":"0.1.0","private":true,"type":"module","dependencies":{"@modelcontextprotocol/ext-apps":"^1.7.5","@modelcontextprotocol/sdk":"1.32.1","@second-opinion/engine":"*","@second-opinion/notify":"*","@second-opinion/policy":"*","@second-opinion/shared":"*","@second-opinion/store":"*","express":"^5.2.1","zod":"^4.0.0"},"devDependencies":{"esbuild":"^0.28.2"}}
2 changes: 2 additions & 0 deletions apps/mcp-server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { registerPlaceHold } from './tools/placeHold';
import { registerRequestFamilyApproval } from './tools/requestFamilyApproval';
import { registerResolveApproval } from './tools/resolveApproval';
import { registerTrustedPayees } from './tools/trustedPayees';
import { registerCard } from './ui/register';

export const SERVER_NAME = 'second-opinion';
export const SERVER_VERSION = '0.1.0';
Expand All @@ -37,5 +38,6 @@ export function buildServer(deps: Deps): McpServer {
registerListNotifications(server, deps);
registerPolicyTools(server, deps);
registerHouseholdInsights(server, deps);
registerCard(server);
return server;
}
1 change: 1 addition & 0 deletions apps/mcp-server/src/tools/checkMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export function registerCheckMessage(server: McpServer, deps: Deps): void {
decision: decisionSchema,
},
idempotent: true,
ui: true,
annotations: { title: 'Check a message or payment request', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
household: (a) => a.householdId,
handler: ({ householdId, text, channel, context }, ctx) => {
Expand Down
8 changes: 7 additions & 1 deletion apps/mcp-server/src/tools/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { CallToolResult, ToolAnnotations } from '@modelcontextprotocol/sdk/
import { ToolError, ID_PATTERN } from '@second-opinion/shared';
import { z } from 'zod';
import type { Deps } from '../deps';
import { CARD_URI } from '../ui/register';

/** Household/person/hold ids: prefixed, bounded, safe characters. */
export const idSchema = z.string().max(80).regex(ID_PATTERN, 'must look like prefix_id');
Expand Down Expand Up @@ -58,6 +59,8 @@ interface Spec<I extends z.ZodRawShape, O extends z.ZodRawShape> {
annotations: ToolAnnotations;
/** Adds an optional `idempotencyKey` input and `replayed` output. Handlers must be synchronous so the result and its key commit atomically. */
idempotent?: boolean;
/** Show the Second Opinion card (MCP App) when the host can render UI. */
ui?: boolean;
handler: (args: z.infer<z.ZodObject<I>>, ctx: ToolContext) => z.infer<z.ZodObject<O>>;
/** household the call acts on, for audit + logs */
household?: (args: z.infer<z.ZodObject<I>>) => string | undefined;
Expand All @@ -74,7 +77,10 @@ export function defineTool<I extends z.ZodRawShape, O extends z.ZodRawShape>(ser

server.registerTool(
spec.name,
{ title: spec.title, description: spec.description, inputSchema: input, outputSchema: output, annotations: spec.annotations },
{
title: spec.title, description: spec.description, inputSchema: input, outputSchema: output, annotations: spec.annotations,
...(spec.ui ? { _meta: { ui: { resourceUri: CARD_URI }, 'ui/resourceUri': CARD_URI } } : {}),
},
(async (rawArgs: Record<string, unknown>, extra: RequestExtra): Promise<CallToolResult> => {
const started = performance.now();
const traceId = traceIdFrom(extra);
Expand Down
1 change: 1 addition & 0 deletions apps/mcp-server/src/tools/getHold.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function registerGetHold(server: McpServer, deps: Deps): void {
votes: z.array(z.object({ approverId: z.string(), name: z.string(), decision: z.enum(['approve', 'deny']), note: z.string().nullable(), decidedAt: z.string() })),
timeline: z.array(z.object({ type: z.string(), label: z.string(), at: z.string(), by: z.string().nullable() })),
},
ui: true,
annotations: { title: 'Get one held action with its votes and timeline', readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
handler: ({ holdId }) => {
const h = deps.repos.holds.get(holdId);
Expand Down
2 changes: 2 additions & 0 deletions apps/mcp-server/src/ui/card.generated.ts

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions apps/mcp-server/src/ui/register.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { registerAppResource, RESOURCE_MIME_TYPE } from '@modelcontextprotocol/ext-apps/server';
import { CARD_HTML } from './card.generated';

/** MCP App view shown by hosts that render UI (Alexa+ on a screen). Tools without UI support still return full text and structuredContent. */
export const CARD_URI = 'ui://second-opinion/card.html';

export function registerCard(server: McpServer): void {
registerAppResource(
server,
'Second Opinion card',
CARD_URI,
// No network access is needed or declared: the view is a single self-contained document.
{ mimeType: RESOURCE_MIME_TYPE, description: 'Shows the verdict, the red flags and who must approve a request.' },
async () => ({ contents: [{ uri: CARD_URI, mimeType: RESOURCE_MIME_TYPE, text: CARD_HTML }] }),
);
}
46 changes: 46 additions & 0 deletions apps/mcp-server/test/card.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
// @ts-expect-error plain .mjs build script
import { buildCardHtml } from '../../../scripts/build-card.mjs';
import { CARD_HTML } from '../src/ui/card.generated';
import { CARD_URI } from '../src/ui/register';
import { startTestServer } from './helpers';

test('T-CARD-1 the visual tools point at the card and the others do not (MCP Apps metadata)', async () => {
const t = await startTestServer();
try {
const { client } = await t.connect();
const tools = (await client.listTools()).tools;
const meta = (name: string) => (tools.find((x) => x.name === name)?._meta ?? {}) as { ui?: { resourceUri?: string } };
assert.equal(meta('check_message').ui?.resourceUri, CARD_URI);
assert.equal(meta('get_hold').ui?.resourceUri, CARD_URI);
assert.equal(meta('resolve_approval').ui, undefined);
assert.equal(tools.length, 12, 'no tool was added or lost');
await client.close();
} finally {
await t.close();
}
});

test('T-CARD-2 the card is served as an MCP App resource: right MIME type, self-contained, shows the key states', async () => {
const t = await startTestServer();
try {
const { client } = await t.connect();
const listed = (await client.listResources()).resources.find((r) => r.uri === CARD_URI);
assert.ok(listed);
assert.match(listed!.mimeType ?? '', /^text\/html;profile=mcp-app/);
const read = await client.readResource({ uri: CARD_URI });
const html = String((read.contents[0] as { text?: string }).text);
assert.equal(read.contents[0]?.mimeType, listed!.mimeType);
assert.match(html, /^<!doctype html>/i);
assert.doesNotMatch(html, /<script[^>]+src=|<link[^>]+href=|@import/i, 'no external files, so no network permission is needed');
for (const text of ['Paused for your family', 'Be careful', 'Looks fine', 'Alexa cannot approve this']) assert.ok(html.includes(text), text);
await client.close();
} finally {
await t.close();
}
});

test('T-CARD-3 the generated card is up to date with its source (run `npm run build:card` if this fails)', async () => {
assert.equal(CARD_HTML, await buildCardHtml());
});
77 changes: 77 additions & 0 deletions apps/mcp-server/ui/card.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Browser code for the Second Opinion card (an MCP App view). Bundled into one HTML string by scripts/build-card.mjs.
// It only displays what the tool returned; it never decides anything and cannot approve a hold.
import { App } from '@modelcontextprotocol/ext-apps';

type Level = 'allow' | 'caution' | 'hold';
interface CheckShape {
verdict?: Level;
spokenSummary?: string;
card?: { title?: string; level?: Level; flags?: string[]; advice?: string };
decision?: { outcome?: string; reasonText?: string[] };
}
interface HoldShape {
hold?: { status?: string; description?: string; payee?: string | null; amountCents?: number | null };
risk?: { verdict?: Level; flags?: string[] };
votes?: Array<{ name: string; decision: string }>;
}

const LABEL: Record<Level, string> = { hold: 'Paused for your family', caution: 'Be careful', allow: 'Looks fine' };
const STATUS: Record<string, string> = {
pending: 'Waiting for a family member to decide',
released: 'Approved by your family',
denied: 'Your family said no',
expired: 'Timed out, still blocked',
};

const root = document.getElementById('card')!;

function money(cents?: number | null): string {
return typeof cents === 'number' ? `$${(cents / 100).toLocaleString('en-US', { minimumFractionDigits: cents % 100 ? 2 : 0 })}` : '';
}

function render(level: Level, headline: string, flags: string[], advice: string, footer: string): void {
root.className = `card ${level}`;
root.replaceChildren();
const add = (tag: string, cls: string, text: string) => {
const el = document.createElement(tag);
el.className = cls;
el.textContent = text;
root.appendChild(el);
return el;
};
add('div', 'badge', LABEL[level]);
add('p', 'headline', headline);
if (flags.length) {
const ul = document.createElement('ul');
ul.className = 'flags';
for (const f of flags.slice(0, 4)) {
const li = document.createElement('li');
li.textContent = f;
ul.appendChild(li);
}
root.appendChild(ul);
}
if (advice) add('p', 'advice', advice);
if (footer) add('p', 'footer', footer);
}

function show(sc: CheckShape & HoldShape | undefined): void {
if (!sc) return render('caution', 'I could not check this right now.', [], 'Please ask your family before paying.', 'Nothing was done.');
if (sc.hold) {
const level = sc.risk?.verdict ?? 'hold';
const amount = money(sc.hold.amountCents);
const what = [sc.hold.description, amount ? `(${amount})` : ''].filter(Boolean).join(' ');
const votes = (sc.votes ?? []).map((v) => `${v.name}: ${v.decision === 'approve' ? 'yes' : 'no'}`).join(', ');
return render(level, what || 'A request is waiting', sc.risk?.flags ?? [], '', [STATUS[sc.hold.status ?? ''] ?? '', votes].filter(Boolean).join(' · '));
}
const level = sc.card?.level ?? sc.verdict ?? 'caution';
const blocked = sc.decision?.outcome === 'block';
const footer = blocked
? `Not allowed by your family's rules. ${(sc.decision?.reasonText ?? []).join(' ')}`.trim()
: level === 'allow' ? '' : 'Alexa cannot approve this. Only your family can.';
render(level, sc.spokenSummary ?? sc.card?.title ?? '', sc.card?.flags ?? [], sc.card?.advice ?? '', footer);
}

const app = new App({ name: 'Second Opinion card', version: '0.1.0' });
app.ontoolresult = (result) => show(result.structuredContent as (CheckShape & HoldShape) | undefined);
app.connect().catch(() => show(undefined));
2 changes: 1 addition & 1 deletion docs/alexa-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
| OAuth 2.1 authorization code + PKCE (S256), `resource` parameter, protected-resource metadata, authorization-server metadata, static client (no dynamic registration), 401 without `WWW-Authenticate` | **Done** (`apps/mcp-server/src/oauth.ts`, tests T-OAUTH-1 to 9) |
| Round trip under 500 ms | Likely (the engine takes about a millisecond and tools are synchronous SQLite), **not measured against Alexa+**. Measure through the tunnel |
| Add-on package (`addon.json`, icons, carousel image, privacy and terms URLs) | Template only: `alexa-addon/addon.json`. Needs real URLs and artwork |
| Text-only is allowed (MCP Apps visuals optional) | OK |
| Visuals via the MCP Apps standard (optional) | **Done**: `check_message` and `get_hold` link to a `ui://second-opinion/card.html` view (verdict, red flags, who must approve), authored for Alexa's 768x480 reference size, self-contained (no network), with text fallback for voice-only devices. Tested at protocol level (T-CARD-1 to 3) and rendered in a browser with a stand-in host; **not yet seen on a real Alexa+ screen** |
| Elicitation (Alexa+ asking the user to confirm) | Not covered by the quickstart page we read; not implemented |

## Account linking: how OAuth works here
Expand Down
Binary file added docs/assets/alexa-card-hold.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ Log later changes below with date and impact on other docs.
| 2026-10-09 | D19: published `rules-2026.10.4` (rule pack v3, playbook pack p3, new signal `ADVANCE_FEE`, hard rule `ADVANCE_FEE_PLUS_PRESSURE`). Rule sets 10.1-10.3 are frozen by golden tests. Before changing the detector we wrote bench split `test2` (40 scripts) and scored 10.1-10.3 on it; 10.4 was scored once. Caveat recorded in `eval-report.md`: the same author wrote test2 and the v4 rules, so the 95% is not a generalisation claim. |
| 2026-10-09 | D20: replaced `better-sqlite3` with Node's built-in `node:sqlite` (Node >= 22.13, thin `Db` wrapper in `packages/store/src/db.ts`). Reason: a clean `npm install` on Windows tried to compile the native module and failed without Visual Studio; judges must be able to run `npm install && npm run demo`. Resolves D9. Cost: Node prints an ExperimentalWarning for `node:sqlite` on 22.x. |
| 2026-10-10 | D21: added OAuth 2.1 (auth code + PKCE S256, static client, signed stateless tokens) because the Alexa+ MCP Toolkit requires it; an assistant token cannot call `resolve_approval` or `set_policy` and is bound to one household. Added `FIXED_NOW` so tests do not depend on the time of day (a simulator test failed after 22:00 Chicago time). The live Alexa+ connection is still **not** done or verified. |
| 2026-10-10 | D22: added an MCP Apps view (`ui://second-opinion/card.html`, `@modelcontextprotocol/ext-apps` 1.7.5, the 1.x line that matches SDK 1.32.1; 2.x needs the v2 SDK). Bundled into one HTML string by `scripts/build-card.mjs` (committed output, a test fails if stale). Rationale: Alexa+ renders MCP-App UI on screens and the rules list MCP Apps as a creative signal. Not verified on a real Alexa+ device. |
Loading
Loading