Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(agent-context): add local read-only MCP surface (#4411)
[._.]/ Adam Eivy361963e473ac
diff --git a/.changelog/next/added-issue-4411.md b/.changelog/next/added-issue-4411.mdnew file mode 100644index 0000000000..95f847aa97--- /dev/null+++ b/.changelog/next/added-issue-4411.md@@ -0,0 +1 @@+- Added an opt-in, loopback-only MCP agent-context surface with bounded read-only tools, privacy profiles, and Settings controls (#4411).diff --git a/client/src/components/settings/ApiAccessTab.jsx b/client/src/components/settings/ApiAccessTab.jsxindex e1333f86d7..c085e4afb1 100644--- a/client/src/components/settings/ApiAccessTab.jsx+++ b/client/src/components/settings/ApiAccessTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback } from 'react';-import { Globe, Lock, Unlock, Copy, RefreshCw } from 'lucide-react';+import { Bot, Globe, Lock, Unlock, Copy, RefreshCw } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import { getSettings, updateSettings, getOpenApiSpec } from '../../services/apiSystem';@@ -34,27 +34,37 @@ const API_CARDS = [];const DEFAULT_ACCESS = { exposed: false, requireAuth: false };+const DEFAULT_AGENT_CONTEXT = { enabled: false, profile: 'metadata', scopes: ['navigation', 'workspaces'] };+const AGENT_CONTEXT_SCOPES = [+ { id: 'navigation', label: 'Navigation', hint: 'PortOS page labels, aliases, and paths.' },+ { id: 'workspaces', label: 'Workspaces', hint: 'App presence and task counts; never repository paths or branches.' },+ { id: 'brain', label: 'Brain', hint: 'Searchable Brain records; metadata-only unless summary mode is selected.' },+ { id: 'identity', label: 'Identity export', hint: 'Section presence only; never raw identity records or Privacy Vault data.' },+];-const Toggle = ({ checked, onChange, label, hint, disabled }) => (- <label className={`flex items-start gap-3 ${disabled ? 'opacity-50' : 'cursor-pointer'}`}>+const Toggle = ({ id, checked, onChange, label, hint, disabled }) => (+ <div className={`flex items-start gap-3 ${disabled ? 'opacity-50' : ''}`}><input+ id={id}+ aria-label={label}type="checkbox"checked={checked}disabled={disabled}onChange={(e) => onChange(e.target.checked)}className="w-4 h-4 mt-0.5 shrink-0"/>- <div className="flex flex-col min-w-0 flex-1">+ <label htmlFor={id} className={`flex flex-col min-w-0 flex-1 ${disabled ? '' : 'cursor-pointer'}`}><span className="text-sm text-white">{label}</span>{hint && <span className="text-xs text-gray-500">{hint}</span>}- </div>- </label>+ </label>+ </div>);export function ApiAccessTab() {const [loading, setLoading] = useState(true);const [savingId, setSavingId] = useState(null);const [access, setAccess] = useState({});+ const [agentContext, setAgentContext] = useState(DEFAULT_AGENT_CONTEXT);const [spec, setSpec] = useState(null);// window.location.origin is the tailnet host the user is browsing from, so@@ -69,7 +79,14 @@ export function ApiAccessTab() {useEffect(() => {getSettings({ silent: true })- .then((s) => setAccess(s?.apiAccess || {}))+ .then((s) => {+ setAccess(s?.apiAccess || {});+ setAgentContext({+ ...DEFAULT_AGENT_CONTEXT,+ ...(s?.agentContext || {}),+ scopes: s?.agentContext?.scopes?.length ? s.agentContext.scopes : DEFAULT_AGENT_CONTEXT.scopes,+ });+ }).catch(() => toast.error('Failed to load API access settings')).finally(() => setLoading(false));loadSpec();@@ -98,6 +115,28 @@ export function ApiAccessTab() {}};+ const patchAgentContext = async (partial) => {+ const prev = agentContext;+ const next = { ...prev, ...partial };+ setAgentContext(next);+ setSavingId('agent-context');+ try {+ await updateSettings({ agentContext: next }, { silent: true });+ } catch (err) {+ setAgentContext(prev);+ toast.error(`Failed to save: ${err.message}`);+ } finally {+ setSavingId(null);+ }+ };++ const patchAgentContextScope = (scope, checked) => {+ const scopes = checked+ ? [...new Set([...agentContext.scopes, scope])]+ : agentContext.scopes.filter((candidate) => candidate !== scope);+ if (scopes.length > 0) patchAgentContext({ scopes });+ };+if (loading) return <BrailleSpinner text="Loading API access settings" />;return (@@ -147,6 +186,7 @@ export function ApiAccessTab() {<div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><Toggle+ id={`api-${card.id}-exposed`}checked={entry.exposed}disabled={busy}onChange={(v) => patchAccess(card.id, { exposed: v })}@@ -154,6 +194,7 @@ export function ApiAccessTab() {hint="Off by default. Nothing is reachable until you turn this on."/><Toggle+ id={`api-${card.id}-auth`}checked={entry.requireAuth}disabled={busy || !entry.exposed}onChange={(v) => patchAccess(card.id, { requireAuth: v })}@@ -190,6 +231,82 @@ export function ApiAccessTab() {);})}+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2 text-white">+ <Bot size={18} />+ <h3 className="text-base font-semibold">Agent Context (MCP)</h3>+ <span className={`text-xs ${agentContext.enabled ? 'text-port-success' : 'text-gray-500'}`}>+ {agentContext.enabled ? 'local access enabled' : 'disabled'}+ </span>+ </div>+ <p className="text-xs text-gray-500 mt-1">+ A read-only context surface for agents running on this machine. It accepts loopback+ connections only, never tailnet or public traffic, and makes no LLM calls. PortOS+ password authentication still applies when configured.+ </p>+ </div>+ {savingId === 'agent-context' && <BrailleSpinner />}+ </div>++ <Toggle+ id="agent-context-enabled"+ checked={agentContext.enabled}+ disabled={savingId !== null}+ onChange={(enabled) => patchAgentContext({ enabled })}+ label="Enable local MCP context"+ hint="Off by default. Enabling does not expose the endpoint beyond this machine."+ />++ <fieldset className="space-y-2" disabled={savingId !== null}>+ <legend className="text-xs font-medium text-gray-300 mb-2">Allowed context scopes</legend>+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ {AGENT_CONTEXT_SCOPES.map((scope) => {+ const checked = agentContext.scopes.includes(scope.id);+ return (+ <Toggle+ key={scope.id}+ id={`agent-context-scope-${scope.id}`}+ checked={checked}+ disabled={savingId !== null || (checked && agentContext.scopes.length === 1)}+ onChange={(value) => patchAgentContextScope(scope.id, value)}+ label={scope.label}+ hint={scope.hint}+ />+ );+ })}+ </div>+ </fieldset>++ <div className="space-y-1">+ <label htmlFor="agent-context-profile" className="text-xs font-medium text-gray-300">Disclosure profile</label>+ <select+ id="agent-context-profile"+ value={agentContext.profile}+ disabled={savingId !== null}+ onChange={(event) => patchAgentContext({ profile: event.target.value })}+ className="block w-full sm:max-w-md bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white disabled:opacity-50"+ >+ <option value="metadata">Metadata only (recommended)</option>+ <option value="summary">Redacted summaries</option>+ </select>+ <p className="text-xs text-gray-500">+ Metadata mode can match private text but returns only generic record labels and stable opaque references.+ </p>+ </div>++ <div className="space-y-1">+ <div className="text-xs text-gray-400">Local Streamable HTTP endpoint</div>+ <code className="block bg-port-bg border border-port-border rounded-lg px-3 py-2 text-xs text-port-accent break-all">+ /api/agent-context/mcp+ </code>+ <p className="text-xs text-gray-500">+ Runtime manifest: <code className="text-port-accent">/api/agent-context/manifest</code>+ </p>+ </div>+ </div>+<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-2"><div className="flex items-center justify-between gap-2"><h3 className="text-base font-semibold text-white">OpenAPI spec</h3>diff --git a/client/src/components/settings/ApiAccessTab.test.jsx b/client/src/components/settings/ApiAccessTab.test.jsxindex c5c2c2d42b..935e404308 100644--- a/client/src/components/settings/ApiAccessTab.test.jsx+++ b/client/src/components/settings/ApiAccessTab.test.jsx@@ -109,4 +109,44 @@ describe('ApiAccessTab', () => {// Both cards show "not exposed".expect(screen.getAllByText('not exposed').length).toBe(2);});++ it('defaults agent context to disabled metadata with minimal scopes', async () => {+ getSettings.mockResolvedValue({});+ await renderTab();+ expect(screen.getByLabelText('Enable local MCP context').checked).toBe(false);+ expect(screen.getByLabelText('Navigation').checked).toBe(true);+ expect(screen.getByLabelText('Workspaces').checked).toBe(true);+ expect(screen.getByLabelText('Brain').checked).toBe(false);+ expect(screen.getByLabelText('Disclosure profile').value).toBe('metadata');+ });++ it('persists the complete agent-context opt-in configuration', async () => {+ getSettings.mockResolvedValue({});+ await renderTab();+ fireEvent.click(screen.getByLabelText('Enable local MCP context'));+ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({+ agentContext: {+ enabled: true,+ profile: 'metadata',+ scopes: ['navigation', 'workspaces'],+ },+ }, { silent: true }));+ });++ it('serializes agent-context scope saves with all API toggles', async () => {+ getSettings.mockResolvedValue({+ agentContext: { enabled: true, profile: 'metadata', scopes: ['navigation', 'workspaces'] },+ });+ let resolveSave;+ updateSettings.mockReturnValue(new Promise((resolve) => { resolveSave = resolve; }));+ await renderTab();+ fireEvent.click(screen.getByLabelText('Brain'));++ await waitFor(() => {+ expect(screen.getAllByLabelText(/Expose on the network/i)[0].disabled).toBe(true);+ expect(screen.getByLabelText('Disclosure profile').disabled).toBe(true);+ });+ expect(updateSettings.mock.calls[0][0].agentContext.scopes).toEqual(['navigation', 'workspaces', 'brain']);+ await act(async () => { resolveSave({}); });+ });});diff --git a/docs/API.md b/docs/API.mdindex c67d2170c0..60ea25e06f 100644--- a/docs/API.md+++ b/docs/API.md@@ -85,6 +85,15 @@ PortOS is designed for personal/developer use on trusted networks. It implements| GET | `/agents/:pid` | Get agent process details || DELETE | `/agents/:pid` | Kill agent process |+### Agent Context (MCP)++| Method | Endpoint | Description |+|--------|----------|-------------|+| GET | `/agent-context/manifest` | Inspect the local context profile, scopes, schemas, exclusions, and limits; available while MCP is disabled |+| POST | `/agent-context/mcp` | Loopback-only, opt-in MCP Streamable HTTP endpoint for bounded read-only context tools |++See [Agent Context (MCP)](./features/agent-context.md) for setup, transport headers, privacy profiles, and tool schemas.+### Command Execution| Method | Endpoint | Description |@@ -479,6 +488,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/avatar` | Avatar rendering/config || `/api/system` | System health metrics || `/api/capabilities` | Feature capability flags |+| `/api/agent-context` | Opt-in, loopback-only read-only MCP context and runtime manifest || `/api/workspace-contexts` | Workspace context management || `/api/apps/:appId/reference-repos` | Per-app reference repos || `/api/network-exposure` | Network exposure checks |diff --git a/docs/README.md b/docs/README.mdindex ffe8e4670a..0653600e03 100644--- a/docs/README.md+++ b/docs/README.md@@ -32,7 +32,7 @@ Start with the [product surface map](./features/product-surfaces.md) for a complApp management: [app-wizard](./features/app-wizard.md) · [autofixer](./features/autofixer.md) · [browser](./features/browser.md) · [error-handling](./features/error-handling.md) · [jira-sprint-manager](./features/jira-sprint-manager.md)-Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [mtplx](./features/mtplx.md) · [prompt-manager](./features/prompt-manager.md)+Chief of Staff: [chief-of-staff](./features/chief-of-staff.md) · [cos-agent-runner](./features/cos-agent-runner.md) · [cos-enhancement](./features/cos-enhancement.md) · [agent-context](./features/agent-context.md) · [agent-skills](./features/agent-skills.md) · [memory-system](./features/memory-system.md) · [claude-ollama](./features/claude-ollama.md) · [mtplx](./features/mtplx.md) · [prompt-manager](./features/prompt-manager.md)Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system](./features/identity-system.md) · [soul-system](./features/soul-system.md) · [post](./features/post.md) (insights design spike: [plans/2026-06-03](./plans/2026-06-03-cross-domain-insights-engine.md))diff --git a/docs/features/agent-context.md b/docs/features/agent-context.mdnew file mode 100644index 0000000000..4aa853e32b--- /dev/null+++ b/docs/features/agent-context.md@@ -0,0 +1,79 @@+# Agent Context (MCP)++PortOS can expose a bounded, read-only context surface to agents running on the same machine. The surface uses MCP Streamable HTTP, is disabled by default, and never initiates an LLM request.++## Enable it++Open **Settings → API Access → Agent Context (MCP)** and enable **local MCP context**. The setting is stored machine-locally in the existing `settings.json` store; no context data is copied into a new store.++The endpoint is:++```text+/api/agent-context/mcp+```++Use `http://127.0.0.1:5555` when PortOS is running over HTTP. When PortOS HTTPS is enabled, local scripts can use the loopback HTTP mirror on `http://127.0.0.1:5553`. The runtime manifest is available at `GET /api/agent-context/manifest` even while the MCP endpoint is disabled.++## Network and authentication boundary++The route checks the TCP socket address, not forwarding headers, and accepts only IPv4 or IPv6 loopback callers. A supplied `Origin` header must also identify a loopback origin. Tailnet, LAN, public, proxied, and federated callers are rejected.++The normal PortOS authentication gate runs before this route. If an instance password is enabled, the MCP client must also send a valid PortOS session, Bearer token, or Basic credential.++This first transport is intentionally stateless: it emits no MCP session identifier, accepts JSON responses to POST, and returns `405` for GET/DELETE on the MCP endpoint. It implements protocol version `2025-11-25` and recognizes the compatible `2025-03-26` and `2025-06-18` request headers.++## Disclosure profiles and scopes++The default profile is **Metadata only** with only **Navigation** and **Workspaces** enabled.++| Profile | Returned content |+|---|---|+| Metadata only | Generic record labels, bounded counts, routes, and opaque stable references. Private text can be used for matching but is not returned. |+| Redacted summaries | Selected source summaries after high-confidence secret, email, IP address, home-directory, phone, and explicit coordinate redaction. This is an additional opt-in, not an anonymization guarantee. |++Scopes are independently configurable:++| Scope | Source | Privacy behavior |+|---|---|---|+| Navigation | PortOS navigation manifest | Page labels, aliases, sections, and routes only. |+| Workspaces | Workspace context summaries | Task counts; repository paths, branches, shell sessions, and raw app identifiers are excluded. Workspace identifiers become opaque hashes. |+| Brain | Brain search projections | Opaque record references in metadata mode; redacted projected text only in summary mode. Only projected fields become context candidates; attachments, embeddings, and full records are never returned. |+| Identity | Legacy identity-export preview | Section labels and presence only. Raw export records and generated export files are never returned. |++Privacy Vault records, credentials, secrets, authentication material, federation peers, network topology, machine identity, command/browser/message history, health records, and raw personal exports are excluded from every profile.++## Tools and budgets++All advertised tools carry MCP `readOnlyHint: true`, `destructiveHint: false`, `idempotentHint: true`, and `openWorldHint: false`. Their advertised JSON Schemas are generated from the same Zod schemas that validate runtime calls and outputs.++| Tool | Purpose |+|---|---|+| `context_profile` | Inspect active scopes, profile, exclusions, and budgets before querying. |+| `search_context` | Search one or more enabled scopes. |+| `get_context` | Resolve one stable opaque reference. |+| `list_context` | Page through one enabled scope. |+| `resolve_navigation` | Resolve a PortOS page alias when Navigation is enabled. |++Calls are capped at 25 returned items, 1,000 inspected source items per scope, 320 characters per summary, 200 characters per query, and 20,000 serialized characters per structured result. Source failures produce an MCP tool error rather than masquerading as an empty result. A capped scan sets `sourceTruncated: true`; search/list also set `truncated: true`, so partial coverage cannot look complete.++## Protocol example++Initialize before listing or calling tools:++```bash+curl -sS http://127.0.0.1:5555/api/agent-context/mcp \+ -H 'content-type: application/json' \+ -H 'accept: application/json, text/event-stream' \+ -d '{+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-11-25",+ "capabilities": {},+ "clientInfo": { "name": "Example Client", "version": "1.0" }+ }+ }'+```++Then send `notifications/initialized` and use `tools/list` or `tools/call` on the same URL. Since the server is stateless, there is no session token to retain.diff --git a/server/index.js b/server/index.jsindex bb5b24074d..6831a0744d 100644--- a/server/index.js+++ b/server/index.js@@ -14,6 +14,7 @@ import appleHealthRoutes from './routes/appleHealth.js';import avatarRoutes from './routes/avatar.js';import systemHealthRoutes from './routes/systemHealth.js';import capabilitiesRoutes from './routes/capabilities.js';+import agentContextMcpRoutes from './routes/agentContextMcp.js';import appsRoutes from './routes/apps/index.js';import workspaceContextsRoutes from './routes/workspaceContexts.js';import referenceReposRoutes from './routes/referenceRepos.js';@@ -234,6 +235,7 @@ app.use('/api/alerts', alertsRoutes);app.use('/api/avatar', avatarRoutes);app.use('/api/system', systemHealthRoutes);app.use('/api/capabilities', capabilitiesRoutes);+app.use('/api/agent-context', agentContextMcpRoutes);app.use('/api/apps', appsRoutes);app.use('/api/workspace-contexts', workspaceContextsRoutes);app.use('/api/apps/:appId/reference-repos', referenceReposRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex c72388767d..e00f9a29c7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -23,6 +23,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `agentContextValidation.js` | Shared settings, MCP request/tool input/output schemas, bounds, and `advertiseAgentContextTools(scopes)` for the opt-in read-only agent-context surface. || `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. || `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). || `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |diff --git a/server/lib/agentContextValidation.js b/server/lib/agentContextValidation.jsnew file mode 100644index 0000000000..c5ad5c71dd--- /dev/null+++ b/server/lib/agentContextValidation.js@@ -0,0 +1,191 @@+import { z } from 'zod';++export const AGENT_CONTEXT_SCHEMA_VERSION = 1;+export const AGENT_CONTEXT_PROTOCOL_VERSION = '2025-11-25';+export const AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([+ '2025-03-26',+ '2025-06-18',+ AGENT_CONTEXT_PROTOCOL_VERSION,+]);++export const AGENT_CONTEXT_SCOPES = Object.freeze(['navigation', 'workspaces', 'brain', 'identity']);+export const AGENT_CONTEXT_PROFILES = Object.freeze(['metadata', 'summary']);+export const AGENT_CONTEXT_DEFAULT_SCOPES = Object.freeze(['navigation', 'workspaces']);+export const AGENT_CONTEXT_LIMITS = Object.freeze({+ defaultResults: 10,+ maxResults: 25,+ maxSummaryChars: 320,+ maxResponseChars: 20_000,+ maxSourceItems: 1_000,+ maxQueryChars: 200,+ maxRefChars: 180,+});++const uniqueScopes = (scopes) => new Set(scopes).size === scopes.length;++export const agentContextSettingsSchema = z.object({+ enabled: z.boolean().optional(),+ profile: z.enum(AGENT_CONTEXT_PROFILES).optional(),+ scopes: z.array(z.enum(AGENT_CONTEXT_SCOPES))+ .min(1)+ .max(AGENT_CONTEXT_SCOPES.length)+ .refine(uniqueScopes, 'Scopes must be unique')+ .optional(),+}).strict();++const requestedScopesSchema = z.array(z.enum(AGENT_CONTEXT_SCOPES))+ .min(1)+ .max(AGENT_CONTEXT_SCOPES.length)+ .refine(uniqueScopes, 'Scopes must be unique')+ .optional();++export const agentContextSearchInputSchema = z.object({+ query: z.string().trim().min(1).max(AGENT_CONTEXT_LIMITS.maxQueryChars),+ scopes: requestedScopesSchema,+ limit: z.number().int().min(1).max(AGENT_CONTEXT_LIMITS.maxResults).optional(),+}).strict();++export const agentContextGetInputSchema = z.object({+ ref: z.string().trim().min(1).max(AGENT_CONTEXT_LIMITS.maxRefChars),+}).strict();++export const agentContextListInputSchema = z.object({+ scope: z.enum(AGENT_CONTEXT_SCOPES),+ cursor: z.number().int().min(0).optional(),+ limit: z.number().int().min(1).max(AGENT_CONTEXT_LIMITS.maxResults).optional(),+}).strict();++export const agentContextNavigationInputSchema = z.object({+ query: z.string().trim().min(1).max(AGENT_CONTEXT_LIMITS.maxQueryChars),+}).strict();++export const agentContextProfileInputSchema = z.object({}).strict();++export const agentContextItemSchema = z.object({+ ref: z.string().max(AGENT_CONTEXT_LIMITS.maxRefChars),+ scope: z.enum(AGENT_CONTEXT_SCOPES),+ kind: z.string().max(80),+ title: z.string().max(160),+ summary: z.string().max(AGENT_CONTEXT_LIMITS.maxSummaryChars),+ path: z.string().max(300).optional(),+}).strict();++export const agentContextSearchOutputSchema = z.object({+ items: z.array(agentContextItemSchema).max(AGENT_CONTEXT_LIMITS.maxResults),+ total: z.number().int().min(0),+ truncated: z.boolean(),+ sourceTruncated: z.boolean(),+}).strict();++export const agentContextGetOutputSchema = z.object({+ item: agentContextItemSchema.nullable(),+ sourceTruncated: z.boolean(),+}).strict();++export const agentContextListOutputSchema = z.object({+ items: z.array(agentContextItemSchema).max(AGENT_CONTEXT_LIMITS.maxResults),+ total: z.number().int().min(0),+ nextCursor: z.number().int().min(0).nullable(),+ truncated: z.boolean(),+ sourceTruncated: z.boolean(),+}).strict();++export const agentContextNavigationOutputSchema = z.object({ match: agentContextItemSchema.nullable() }).strict();++export const agentContextProfileOutputSchema = z.object({+ profile: z.enum(AGENT_CONTEXT_PROFILES),+ scopes: z.array(z.enum(AGENT_CONTEXT_SCOPES)),+ limits: z.object({+ defaultResults: z.number().int().positive(),+ maxResults: z.number().int().positive(),+ maxSummaryChars: z.number().int().positive(),+ maxResponseChars: z.number().int().positive(),+ maxSourceItems: z.number().int().positive(),+ }).strict(),+ exclusions: z.array(z.string()),+}).strict();++export const agentContextMcpRequestSchema = z.object({+ jsonrpc: z.literal('2.0'),+ id: z.union([z.string().max(200), z.number().finite()]),+ method: z.string().min(1).max(120),+ params: z.record(z.string(), z.unknown()).optional(),+}).strict();++export const agentContextMcpNotificationSchema = z.object({+ jsonrpc: z.literal('2.0'),+ method: z.string().min(1).max(120),+ params: z.record(z.string(), z.unknown()).optional(),+}).strict();++export const agentContextMcpResponseSchema = z.object({+ jsonrpc: z.literal('2.0'),+ id: z.union([z.string().max(200), z.number().finite()]),+ result: z.unknown().optional(),+ error: z.unknown().optional(),+}).strict().refine((value) => value.result !== undefined || value.error !== undefined, {+ message: 'A response requires result or error',+});++export const agentContextMcpInboundSchema = z.union([+ agentContextMcpRequestSchema,+ agentContextMcpNotificationSchema,+ agentContextMcpResponseSchema,+]);++export const agentContextInitializeParamsSchema = z.object({+ protocolVersion: z.string().max(40),+ capabilities: z.record(z.string(), z.unknown()),+ clientInfo: z.object({+ name: z.string().min(1).max(120),+ version: z.string().min(1).max(80),+ title: z.string().max(160).optional(),+ websiteUrl: z.url().max(500).optional(),+ icons: z.array(z.object({+ src: z.string().min(1).max(500),+ mimeType: z.string().max(120).optional(),+ sizes: z.array(z.string().max(40)).max(20).optional(),+ theme: z.enum(['light', 'dark']).optional(),+ }).strict()).max(20).optional(),+ }).strict(),+ _meta: z.record(z.string(), z.unknown()).optional(),+}).strict();++export const agentContextToolsListParamsSchema = z.object({+ cursor: z.string().min(1).max(200).optional(),+ _meta: z.record(z.string(), z.unknown()).optional(),+}).strict();++export const agentContextToolCallParamsSchema = z.object({+ name: z.string().min(1).max(120),+ arguments: z.record(z.string(), z.unknown()).optional(),+ _meta: z.record(z.string(), z.unknown()).optional(),+}).strict();++const toolSpecs = [+ { name: 'search_context', title: 'Search PortOS context', description: 'Search enabled read-only context scopes with bounded results.', inputSchema: agentContextSearchInputSchema, outputSchema: agentContextSearchOutputSchema },+ { name: 'get_context', title: 'Get PortOS context item', description: 'Resolve one stable context reference from an enabled scope.', inputSchema: agentContextGetInputSchema, outputSchema: agentContextGetOutputSchema },+ { name: 'list_context', title: 'List PortOS context', description: 'List a bounded page from one enabled read-only context scope.', inputSchema: agentContextListInputSchema, outputSchema: agentContextListOutputSchema },+ { name: 'resolve_navigation', title: 'Resolve PortOS navigation', description: 'Resolve a PortOS page from its navigation aliases.', inputSchema: agentContextNavigationInputSchema, outputSchema: agentContextNavigationOutputSchema, requiredScope: 'navigation' },+ { name: 'context_profile', title: 'Describe PortOS context access', description: 'Return the active context profile, scopes, exclusions, and budgets.', inputSchema: agentContextProfileInputSchema, outputSchema: agentContextProfileOutputSchema },+];++const toAdvertisedSchema = (schema) => {+ const output = z.toJSONSchema(schema);+ delete output.$schema;+ return output;+};++export const AGENT_CONTEXT_TOOL_REGISTRY = Object.freeze(toolSpecs.map((tool) => Object.freeze(tool)));++export const advertiseAgentContextTools = (scopes = AGENT_CONTEXT_DEFAULT_SCOPES) =>+ AGENT_CONTEXT_TOOL_REGISTRY+ .filter((tool) => !tool.requiredScope || scopes.includes(tool.requiredScope))+ .map((tool) => ({+ name: tool.name,+ title: tool.title,+ description: tool.description,+ inputSchema: toAdvertisedSchema(tool.inputSchema),+ outputSchema: toAdvertisedSchema(tool.outputSchema),+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ }));diff --git a/server/lib/agentContextValidation.test.js b/server/lib/agentContextValidation.test.jsnew file mode 100644index 0000000000..5886a5729f--- /dev/null+++ b/server/lib/agentContextValidation.test.js@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';+import { z } from 'zod';+import {+ AGENT_CONTEXT_LIMITS,+ AGENT_CONTEXT_TOOL_REGISTRY,+ advertiseAgentContextTools,+ agentContextSettingsSchema,+} from './agentContextValidation.js';++const advertisedSchema = (schema) => {+ const output = z.toJSONSchema(schema);+ delete output.$schema;+ return output;+};++describe('agentContextValidation', () => {+ it('accepts only bounded, unique known settings scopes', () => {+ expect(agentContextSettingsSchema.parse({ enabled: true, profile: 'metadata', scopes: ['navigation', 'brain'] }))+ .toEqual({ enabled: true, profile: 'metadata', scopes: ['navigation', 'brain'] });+ expect(agentContextSettingsSchema.safeParse({ scopes: ['brain', 'brain'] }).success).toBe(false);+ expect(agentContextSettingsSchema.safeParse({ scopes: ['privacy-vault'] }).success).toBe(false);+ expect(agentContextSettingsSchema.safeParse({ enabled: true, unknown: true }).success).toBe(false);+ });++ it('advertises the same schemas used for runtime validation', () => {+ const advertised = advertiseAgentContextTools(['navigation', 'workspaces']);+ for (const tool of advertised) {+ const runtime = AGENT_CONTEXT_TOOL_REGISTRY.find((candidate) => candidate.name === tool.name);+ expect(tool.inputSchema).toEqual(advertisedSchema(runtime.inputSchema));+ expect(tool.outputSchema).toEqual(advertisedSchema(runtime.outputSchema));+ }+ });++ it('marks every advertised tool as read-only and non-destructive', () => {+ for (const tool of advertiseAgentContextTools(['navigation', 'workspaces'])) {+ expect(tool.annotations).toEqual({+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: true,+ openWorldHint: false,+ });+ }+ });++ it('enforces result limits in tool input schemas', () => {+ const search = AGENT_CONTEXT_TOOL_REGISTRY.find((tool) => tool.name === 'search_context');+ expect(search.inputSchema.safeParse({ query: 'x', limit: AGENT_CONTEXT_LIMITS.maxResults }).success).toBe(true);+ expect(search.inputSchema.safeParse({ query: 'x', limit: AGENT_CONTEXT_LIMITS.maxResults + 1 }).success).toBe(false);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 0afac106d7..e9d6a57f41 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -17,6 +17,7 @@// `digitalTwinValidation.X`. The catch-all `validation.js` stays flat — its// names are the canonical PortOS-wide schemas.export * as agentValidation from './agentValidation.js';+export * as agentContextValidation from './agentContextValidation.js';export * as appleHealthValidation from './appleHealthValidation.js';export * as brainValidation from './brainValidation.js';export * as catalogValidation from './catalogValidation.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 064c250c8a..9e7fc39848 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1296,3 +1296,4 @@ export * from './mediaValidation.js';export * from './pipelineValidation.js';export * from './quotaBurnValidation.js';export * from './spriteValidation.js';+export * from './agentContextValidation.js';diff --git a/server/routes/agentContextMcp.js b/server/routes/agentContextMcp.jsnew file mode 100644index 0000000000..2726954f22--- /dev/null+++ b/server/routes/agentContextMcp.js@@ -0,0 +1,170 @@+import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import {+ AGENT_CONTEXT_PROTOCOL_VERSION,+ AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS,+ agentContextInitializeParamsSchema,+ agentContextMcpInboundSchema,+ agentContextMcpNotificationSchema,+ agentContextMcpResponseSchema,+ agentContextToolCallParamsSchema,+ agentContextToolsListParamsSchema,+} from '../lib/agentContextValidation.js';+import { callAgentContextTool, getAgentContextManifest } from '../services/agentContextMcp.js';++const router = Router();++const stripAddressDecorations = (address) => String(address ?? '')+ .replace(/^\[|\]$/g, '')+ .split('%', 1)[0]+ .toLowerCase();++export function isLoopbackAddress(address) {+ const normalized = stripAddressDecorations(address);+ if (normalized === '::1' || normalized === 'localhost') return true;+ const ipv4 = normalized.startsWith('::ffff:') ? normalized.slice(7) : normalized;+ const octets = ipv4.split('.');+ return octets.length === 4+ && octets[0] === '127'+ && octets.every((octet) => /^\d{1,3}$/.test(octet) && Number(octet) <= 255);+}++export function isAllowedAgentContextOrigin(origin) {+ if (!origin) return true;+ return URL.canParse(origin) && isLoopbackAddress(new URL(origin).hostname);+}++const requireLocalRequest = (req, _res, next) => {+ if (!isLoopbackAddress(req.socket.remoteAddress)) {+ throw new ServerError('Agent context accepts loopback connections only', {+ status: 403,+ code: 'AGENT_CONTEXT_LOCAL_ONLY',+ });+ }+ if (!isAllowedAgentContextOrigin(req.get('origin'))) {+ throw new ServerError('Agent context rejected a non-loopback Origin', {+ status: 403,+ code: 'AGENT_CONTEXT_ORIGIN_REJECTED',+ });+ }+ next();+};++const requireEnabled = asyncHandler(async (req, _res, next) => {+ const manifest = await getAgentContextManifest();+ if (!manifest.enabled || !manifest.configurationValid) {+ throw new ServerError('Agent context is disabled', {+ status: 403,+ code: 'AGENT_CONTEXT_DISABLED',+ });+ }+ req.agentContextManifest = manifest;+ next();+});++const jsonRpcError = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });+const jsonRpcResult = (id, result) => ({ jsonrpc: '2.0', id, result });++const requireMcpAccept = (req, res) => {+ const accept = String(req.get('accept') ?? '').toLowerCase();+ if (accept.includes('application/json') && accept.includes('text/event-stream')) return true;+ res.status(406).json(jsonRpcError(null, -32600, 'Accept must include application/json and text/event-stream'));+ return false;+};++const protocolHeaderIsSupported = (req) => {+ const version = req.get('mcp-protocol-version');+ return !version || AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS.includes(version);+};++router.use(requireLocalRequest);++router.get('/manifest', asyncHandler(async (_req, res) => {+ res.json(await getAgentContextManifest());+}));++router.use('/mcp', requireEnabled);++router.get('/mcp', (_req, res) => {+ res.set('Allow', 'POST').status(405).end();+});++router.delete('/mcp', (_req, res) => {+ res.set('Allow', 'POST').status(405).end();+});++router.post('/mcp', asyncHandler(async (req, res) => {+ if (!requireMcpAccept(req, res)) return;+ if (!protocolHeaderIsSupported(req)) {+ res.status(400).json(jsonRpcError(null, -32600, 'Unsupported MCP-Protocol-Version'));+ return;+ }++ const parsed = agentContextMcpInboundSchema.safeParse(req.body);+ if (!parsed.success) {+ res.status(400).json(jsonRpcError(null, -32600, 'Invalid JSON-RPC message'));+ return;+ }++ const message = parsed.data;+ if (agentContextMcpNotificationSchema.safeParse(message).success+ || agentContextMcpResponseSchema.safeParse(message).success) {+ res.status(202).end();+ return;+ }++ if (message.method === 'initialize') {+ const params = agentContextInitializeParamsSchema.safeParse(message.params);+ if (!params.success) {+ res.json(jsonRpcError(message.id, -32602, 'Invalid initialize params'));+ return;+ }+ const requested = params.data.protocolVersion;+ const protocolVersion = AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS.includes(requested)+ ? requested+ : AGENT_CONTEXT_PROTOCOL_VERSION;+ res.json(jsonRpcResult(message.id, {+ protocolVersion,+ capabilities: { tools: { listChanged: false } },+ serverInfo: { name: 'PortOS Agent Context', version: '1' },+ instructions: 'Read-only, local-only context. Inspect context_profile before querying personal scopes.',+ }));+ return;+ }++ if (message.method === 'ping') {+ res.json(jsonRpcResult(message.id, {}));+ return;+ }++ if (message.method === 'tools/list') {+ const params = agentContextToolsListParamsSchema.safeParse(message.params ?? {});+ if (!params.success || params.data.cursor) {+ res.json(jsonRpcError(message.id, -32602, 'Invalid tools/list params'));+ return;+ }+ res.json(jsonRpcResult(message.id, { tools: req.agentContextManifest.tools }));+ return;+ }++ if (message.method === 'tools/call') {+ const params = agentContextToolCallParamsSchema.safeParse(message.params);+ if (!params.success) {+ res.json(jsonRpcError(message.id, -32602, 'Invalid tools/call params'));+ return;+ }+ const result = await callAgentContextTool(params.data.name, params.data.arguments, {+ agentContext: {+ enabled: true,+ profile: req.agentContextManifest.profile,+ scopes: req.agentContextManifest.scopes,+ },+ });+ res.json(jsonRpcResult(message.id, result));+ return;+ }++ res.json(jsonRpcError(message.id, -32601, 'Method not found'));+}));++export default router;diff --git a/server/routes/agentContextMcp.test.js b/server/routes/agentContextMcp.test.jsnew file mode 100644index 0000000000..ec639980d6--- /dev/null+++ b/server/routes/agentContextMcp.test.js@@ -0,0 +1,130 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const mocks = vi.hoisted(() => ({+ getAgentContextManifest: vi.fn(),+ callAgentContextTool: vi.fn(),+}));++vi.mock('../services/agentContextMcp.js', () => ({+ getAgentContextManifest: mocks.getAgentContextManifest,+ callAgentContextTool: mocks.callAgentContextTool,+}));++import agentContextMcpRoutes, { isAllowedAgentContextOrigin, isLoopbackAddress } from './agentContextMcp.js';++const buildApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/agent-context', agentContextMcpRoutes);+ app.use(errorMiddleware);+ return app;+};++const enabledManifest = {+ enabled: true,+ configurationValid: true,+ profile: 'metadata',+ scopes: ['navigation', 'workspaces'],+ tools: [{ name: 'context_profile', inputSchema: { type: 'object' } }],+};++const mcpPost = (body) => request(buildApp())+ .post('/api/agent-context/mcp')+ .set('Accept', 'application/json, text/event-stream')+ .send(body);++describe('agentContextMcp route', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getAgentContextManifest.mockResolvedValue(enabledManifest);+ mocks.callAgentContextTool.mockResolvedValue({ content: [{ type: 'text', text: '{}' }], structuredContent: {} });+ });++ it('recognizes loopback addresses and origins only', () => {+ expect(isLoopbackAddress('127.0.0.1')).toBe(true);+ expect(isLoopbackAddress('::ffff:127.0.0.1')).toBe(true);+ expect(isLoopbackAddress('::1')).toBe(true);+ expect(isLoopbackAddress('127.0.0.999')).toBe(false);+ expect(isLoopbackAddress('192.0.2.10')).toBe(false);+ expect(isAllowedAgentContextOrigin('http://localhost:5555')).toBe(true);+ expect(isAllowedAgentContextOrigin('https://example.com')).toBe(false);+ });++ it('serves a local manifest even while context is disabled', async () => {+ mocks.getAgentContextManifest.mockResolvedValue({ ...enabledManifest, enabled: false });+ const response = await request(buildApp()).get('/api/agent-context/manifest');+ expect(response.status).toBe(200);+ expect(response.body.enabled).toBe(false);+ });++ it('rejects MCP calls while disabled and rejects non-loopback Origins', async () => {+ mocks.getAgentContextManifest.mockResolvedValue({ ...enabledManifest, enabled: false });+ const disabled = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'ping' });+ expect(disabled.status).toBe(403);+ expect(disabled.body.code).toBe('AGENT_CONTEXT_DISABLED');++ mocks.getAgentContextManifest.mockResolvedValue(enabledManifest);+ const origin = await request(buildApp())+ .get('/api/agent-context/manifest')+ .set('Origin', 'https://example.com');+ expect(origin.status).toBe(403);+ expect(origin.body.code).toBe('AGENT_CONTEXT_ORIGIN_REJECTED');+ });++ it('implements initialize negotiation and stateless tools/list', async () => {+ const initialize = await mcpPost({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: { name: 'Example Client', version: '1.0' } },+ });+ expect(initialize.status).toBe(200);+ expect(initialize.body.result.protocolVersion).toBe('2025-11-25');+ expect(initialize.body.result.capabilities.tools).toEqual({ listChanged: false });++ const tools = await mcpPost({ jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} });+ expect(tools.body.result.tools).toEqual(enabledManifest.tools);+ });++ it('dispatches tools/call and acknowledges notifications without a body', async () => {+ const called = await mcpPost({+ jsonrpc: '2.0',+ id: 'call-1',+ method: 'tools/call',+ params: { name: 'context_profile', arguments: {} },+ });+ expect(called.status).toBe(200);+ expect(mocks.callAgentContextTool).toHaveBeenCalledWith('context_profile', {}, {+ agentContext: { enabled: true, profile: 'metadata', scopes: ['navigation', 'workspaces'] },+ });++ const notification = await mcpPost({ jsonrpc: '2.0', method: 'notifications/initialized' });+ expect(notification.status).toBe(202);+ expect(notification.text).toBe('');+ });++ it('enforces transport headers and validated JSON-RPC envelopes', async () => {+ const accept = await request(buildApp())+ .post('/api/agent-context/mcp')+ .set('Accept', 'application/json')+ .send({ jsonrpc: '2.0', id: 1, method: 'ping' });+ expect(accept.status).toBe(406);++ const version = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'ping' })+ .set('MCP-Protocol-Version', '1900-01-01');+ expect(version.status).toBe(400);++ const invalid = await mcpPost({ jsonrpc: '2.0', method: 42 });+ expect(invalid.status).toBe(400);+ expect(invalid.body.error.code).toBe(-32600);+ });++ it('returns 405 for unsupported GET transport', async () => {+ const response = await request(buildApp()).get('/api/agent-context/mcp');+ expect(response.status).toBe(405);+ expect(response.headers.allow).toBe('POST');+ });+});diff --git a/server/routes/settings.js b/server/routes/settings.jsindex aa268d7868..898729ad3c 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -11,6 +11,7 @@ import {} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';import { isPlainObject } from '../lib/objects.js';+import { agentContextSettingsSchema } from '../lib/agentContextValidation.js';import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, autofixerSettingsSchema, codeReviewSettingsSchema, locationSettingsSchema, settingsEmbeddingsSchema, citySnapshotConfigSchema, imessageConfigSchema, signalConfigSchema, spotifyConfigSchema, youtubeConfigSchema, apiAccessSettingsSchema, loraTrainingConfigSchema, pipelineEditorialChecksSettingsSchema, creativeDirectorSettingsSchema, musicSettingsSchema, privacySettingsSchema, seriesAutopilotSettingsSchema, layeredIntelligenceSettingsSchema, imageGenGrokSettingsSchema, imageGenAgySettingsSchema, renderDefaultsSettingsSchema, videoGenSettingsSchema, subscriptionCostsMapSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -206,6 +207,11 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.apiAccess !== undefined) {validateRequest(apiAccessSettingsSchema.partial(), req.body.apiAccess);}+ // Local MCP agent-context opt-in. Validate the whole strict slice so an+ // unknown scope/profile cannot silently broaden what the server exposes.+ if (req.body?.agentContext !== undefined) {+ validateRequest(agentContextSettingsSchema, req.body.agentContext);+ }// Editorial-check enable/config slice (#1284) — validate when present so a// malformed save can't write a non-boolean enabled / non-object config the// registry would then choke on.diff --git a/server/routes/settings.test.js b/server/routes/settings.test.jsindex dcc3dc66bb..8d7512118c 100644--- a/server/routes/settings.test.js+++ b/server/routes/settings.test.js@@ -83,6 +83,38 @@ describe('Settings routes — apiAccess slice', () => {});});+describe('Settings routes — agentContext slice', () => {+ beforeEach(() => {+ store = {};+ vi.clearAllMocks();+ });++ it('accepts and returns a strict disabled-by-default context configuration', async () => {+ const res = await request(buildApp())+ .put('/api/settings')+ .send({ agentContext: { enabled: true, profile: 'metadata', scopes: ['navigation', 'workspaces'] } });+ expect(res.status).toBe(200);+ expect(res.body.agentContext).toEqual({+ enabled: true,+ profile: 'metadata',+ scopes: ['navigation', 'workspaces'],+ });+ });++ it('rejects unknown, empty, duplicate, and misspelled scopes', async () => {+ for (const agentContext of [+ { enabled: true, scopes: [] },+ { enabled: true, scopes: ['brain', 'brain'] },+ { enabled: true, scopes: ['privacy-vault'] },+ { enabled: true, scopes: ['navigation'], extra: true },+ ]) {+ const res = await request(buildApp()).put('/api/settings').send({ agentContext });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ }+ });+});+describe('Settings routes — imageGen.grok slice (#2859)', () => {beforeEach(() => {store = {};diff --git a/server/services/agentContextMcp.js b/server/services/agentContextMcp.jsnew file mode 100644index 0000000000..6e65a47892--- /dev/null+++ b/server/services/agentContextMcp.js@@ -0,0 +1,304 @@+import { createHash } from 'crypto';+import { getSettings } from './settings.js';+import { BRAIN_SEARCH_TYPES, getBrainProjections } from './brainSearchIndex.js';+import { listContexts } from './workspaceContext.js';+import { previewLegacyExport, redactSecrets } from './legacyExport.js';+import { NAV_COMMANDS, resolveNavCommand } from '../lib/navManifest.js';+import {+ AGENT_CONTEXT_DEFAULT_SCOPES,+ AGENT_CONTEXT_LIMITS,+ AGENT_CONTEXT_PROTOCOL_VERSION,+ AGENT_CONTEXT_SCHEMA_VERSION,+ AGENT_CONTEXT_TOOL_REGISTRY,+ advertiseAgentContextTools,+ agentContextSettingsSchema,+} from '../lib/agentContextValidation.js';++export const AGENT_CONTEXT_EXCLUSIONS = Object.freeze([+ 'Privacy Vault and encrypted privacy records',+ 'credentials, secrets, tokens, and authentication material',+ 'federation peers, network topology, and machine identity',+ 'repository paths, branches, shell sessions, and command history',+ 'messages, browser history, health records, and raw personal exports',+]);++const stableId = (value) => createHash('sha256').update(String(value)).digest('hex').slice(0, 20);+const cap = (value, max) => String(value ?? '').slice(0, max);+const normalizedText = (value) => String(value ?? '').replace(/\s+/g, ' ').trim();+const searchableText = (value) => normalizedText(value).slice(0, 2_000);++export function redactAgentContextText(value) {+ return cap(redactSecrets(normalizedText(value))+ .replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi, '[REDACTED EMAIL]')+ .replace(/\b[A-Z0-9-]+(?:\.[A-Z0-9-]+)*\.ts\.net\b/gi, '[REDACTED HOST]')+ .replace(/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, '[REDACTED IP]')+ .replace(/\b(?:[A-F0-9]{1,4}:){2,7}[A-F0-9]{0,4}\b/gi, '[REDACTED IP]')+ .replace(/\b(?:[A-F0-9]{2}:){5}[A-F0-9]{2}\b/gi, '[REDACTED MAC]')+ .replace(/(?:\/Users\/|\/home\/)[^/\s]+/g, '~')+ .replace(/\b(?:\+?\d[\d ().-]{8,}\d)\b/g, '[REDACTED PHONE]')+ .replace(/\b(?:latitude|lat)\s*[:=]\s*-?\d{1,3}(?:\.\d+)?/gi, 'latitude=[REDACTED]')+ .replace(/\b(?:longitude|lon|lng)\s*[:=]\s*-?\d{1,3}(?:\.\d+)?/gi, 'longitude=[REDACTED]'),+ AGENT_CONTEXT_LIMITS.maxSummaryChars);+}++export function resolveAgentContextConfig(settings = {}) {+ const parsed = agentContextSettingsSchema.safeParse(settings.agentContext ?? {});+ if (!parsed.success) {+ return {+ enabled: false,+ profile: 'metadata',+ scopes: [...AGENT_CONTEXT_DEFAULT_SCOPES],+ invalid: true,+ };+ }+ return {+ enabled: parsed.data.enabled ?? false,+ profile: parsed.data.profile ?? 'metadata',+ scopes: parsed.data.scopes ?? [...AGENT_CONTEXT_DEFAULT_SCOPES],+ invalid: false,+ };+}++const navigationItem = (entry) => ({+ item: {+ ref: `navigation:${entry.id}`,+ scope: 'navigation',+ kind: 'page',+ title: cap(entry.label, 160),+ summary: cap(`${entry.section} page in PortOS.`, AGENT_CONTEXT_LIMITS.maxSummaryChars),+ path: cap(entry.path, 300),+ },+ searchText: searchableText([entry.label, entry.section, ...(entry.aliases ?? []), ...(entry.keywords ?? [])].join(' ')),+});++const workspaceItem = (workspace, profile) => ({+ item: {+ ref: `workspaces:workspace:${stableId(workspace.appId)}`,+ scope: 'workspaces',+ kind: 'workspace',+ title: profile === 'summary' ? cap(redactAgentContextText(workspace.appName), 160) : 'Workspace',+ summary: cap(`Active workspace with ${Number(workspace.taskCount) || 0} task(s).`, AGENT_CONTEXT_LIMITS.maxSummaryChars),+ path: '/apps',+ },+ searchText: searchableText(`${workspace.appName} workspace app ${workspace.appId}`),+});++const brainText = (record) => Object.entries(record)+ .filter(([key, value]) => key !== 'id' && key !== '_rank' && typeof value === 'string')+ .map(([, value]) => value)+ .join(' ');++const brainItem = (type, record, profile) => {+ const raw = brainText(record);+ const firstLabel = record.name || record.title || record.oneLiner || record.capturedText || `${type} record`;+ return {+ item: {+ ref: `brain:${type}:${stableId(record.id)}`,+ scope: 'brain',+ kind: type,+ title: profile === 'summary' ? cap(redactAgentContextText(firstLabel), 160) : `${type} record`,+ summary: profile === 'summary'+ ? redactAgentContextText(raw || `Read-only ${type} record.`)+ : `Read-only ${type} record metadata.`,+ path: cap(`/brain/${type}`, 300),+ },+ searchText: searchableText(`${type} ${raw}`),+ };+};++const identityItem = ([key, section]) => ({+ item: {+ ref: `identity:section:${key}`,+ scope: 'identity',+ kind: 'identity-export-section',+ title: cap(section.label || key, 160),+ summary: cap(section.present+ ? 'Present in the local identity export; raw records are excluded.'+ : 'No local identity-export data is present for this section.', AGENT_CONTEXT_LIMITS.maxSummaryChars),+ path: '/digital-twin/time-capsule',+ },+ searchText: searchableText(`${key} ${section.label || ''} identity export ${section.present ? 'present' : 'absent'}`),+});++const SOURCE_LOADERS = Object.freeze({+ navigation: async () => ({+ items: NAV_COMMANDS.slice(0, AGENT_CONTEXT_LIMITS.maxSourceItems).map(navigationItem),+ sourceTruncated: NAV_COMMANDS.length > AGENT_CONTEXT_LIMITS.maxSourceItems,+ }),+ workspaces: async (profile) => {+ const workspaces = await listContexts();+ return {+ items: workspaces.slice(0, AGENT_CONTEXT_LIMITS.maxSourceItems)+ .map((item) => workspaceItem(item, profile)),+ sourceTruncated: workspaces.length > AGENT_CONTEXT_LIMITS.maxSourceItems,+ };+ },+ brain: async (profile) => {+ const byType = await Promise.all(BRAIN_SEARCH_TYPES.map(async (type) => ({+ type,+ records: await getBrainProjections(type),+ })));+ const candidates = [];+ for (const { type, records } of byType) {+ const remaining = AGENT_CONTEXT_LIMITS.maxSourceItems - candidates.length;+ if (remaining <= 0) break;+ candidates.push(...records.slice(0, remaining).map((record) => brainItem(type, record, profile)));+ }+ return {+ items: candidates,+ sourceTruncated: byType.reduce((total, entry) => total + entry.records.length, 0) > candidates.length,+ };+ },+ identity: async () => {+ const sections = Object.entries((await previewLegacyExport()).sections ?? {});+ return {+ items: sections.slice(0, AGENT_CONTEXT_LIMITS.maxSourceItems).map(identityItem),+ sourceTruncated: sections.length > AGENT_CONTEXT_LIMITS.maxSourceItems,+ };+ },+});++const loadItems = async (config, scopes) => {+ const sources = await Promise.all(scopes.map(async (scope) => {+ const loader = SOURCE_LOADERS[scope];+ if (!loader) throw new Error(`Unsupported context scope: ${scope}`);+ return loader(config.profile);+ }));+ return {+ items: sources.flatMap((source) => source.items),+ sourceTruncated: sources.some((source) => source.sourceTruncated),+ };+};++const requestedScopes = (config, scopes) => {+ const requested = scopes ?? config.scopes;+ const unavailable = requested.filter((scope) => !config.scopes.includes(scope));+ if (unavailable.length > 0) throw new Error(`Context scope is not enabled: ${unavailable.join(', ')}`);+ return requested;+};++const fitItems = (items, limit) => {+ const selected = [];+ for (const candidate of items.slice(0, limit)) {+ const next = [...selected, candidate.item];+ if (JSON.stringify(next).length > AGENT_CONTEXT_LIMITS.maxResponseChars) break;+ selected.push(candidate.item);+ }+ return { items: selected, truncated: selected.length < items.length };+};++const profileOutput = (config) => ({+ profile: config.profile,+ scopes: config.scopes,+ limits: {+ defaultResults: AGENT_CONTEXT_LIMITS.defaultResults,+ maxResults: AGENT_CONTEXT_LIMITS.maxResults,+ maxSummaryChars: AGENT_CONTEXT_LIMITS.maxSummaryChars,+ maxResponseChars: AGENT_CONTEXT_LIMITS.maxResponseChars,+ maxSourceItems: AGENT_CONTEXT_LIMITS.maxSourceItems,+ },+ exclusions: [...AGENT_CONTEXT_EXCLUSIONS],+});++const TOOL_HANDLERS = Object.freeze({+ search_context: async (input, config) => {+ const scopes = requestedScopes(config, input.scopes);+ const query = input.query.toLowerCase();+ const loaded = await loadItems(config, scopes);+ const matches = loaded.items+ .filter((candidate) => candidate.searchText.toLowerCase().includes(query));+ const fitted = fitItems(matches, input.limit ?? AGENT_CONTEXT_LIMITS.defaultResults);+ return {+ ...fitted,+ total: matches.length,+ sourceTruncated: loaded.sourceTruncated,+ truncated: fitted.truncated || loaded.sourceTruncated,+ };+ },+ get_context: async (input, config) => {+ const scope = input.ref.split(':', 1)[0];+ if (!config.scopes.includes(scope)) return { item: null, sourceTruncated: false };+ const loaded = await loadItems(config, [scope]);+ return {+ item: loaded.items.find((candidate) => candidate.item.ref === input.ref)?.item ?? null,+ sourceTruncated: loaded.sourceTruncated,+ };+ },+ list_context: async (input, config) => {+ requestedScopes(config, [input.scope]);+ const loaded = await loadItems(config, [input.scope]);+ const all = loaded.items;+ const cursor = input.cursor ?? 0;+ const page = all.slice(cursor);+ const fitted = fitItems(page, input.limit ?? AGENT_CONTEXT_LIMITS.defaultResults);+ const nextOffset = cursor + fitted.items.length;+ return {+ ...fitted,+ total: all.length,+ nextCursor: nextOffset < all.length ? nextOffset : null,+ sourceTruncated: loaded.sourceTruncated,+ truncated: fitted.truncated || loaded.sourceTruncated,+ };+ },+ resolve_navigation: async (input, config) => {+ requestedScopes(config, ['navigation']);+ const match = resolveNavCommand(input.query);+ return { match: match?.command ? navigationItem(match.command).item : null };+ },+ context_profile: async (_input, config) => profileOutput(config),+});++const errorToolResult = (message) => ({+ isError: true,+ content: [{ type: 'text', text: cap(message, 500) }],+});++const successToolResult = (output) => ({+ content: [{ type: 'text', text: JSON.stringify(output) }],+ structuredContent: output,+});++export async function getAgentContextManifest(settings) {+ const current = settings ?? await getSettings();+ const config = resolveAgentContextConfig(current);+ return {+ kind: 'portos-agent-context',+ schemaVersion: AGENT_CONTEXT_SCHEMA_VERSION,+ protocolVersion: AGENT_CONTEXT_PROTOCOL_VERSION,+ enabled: config.enabled,+ configurationValid: !config.invalid,+ transport: {+ type: 'streamable-http',+ endpoint: '/api/agent-context/mcp',+ loopbackOnly: true,+ stateful: false,+ },+ profile: config.profile,+ scopes: config.scopes,+ limits: profileOutput(config).limits,+ exclusions: [...AGENT_CONTEXT_EXCLUSIONS],+ tools: advertiseAgentContextTools(config.scopes),+ };+}++export async function callAgentContextTool(name, args, settings) {+ const current = settings ?? await getSettings();+ const config = resolveAgentContextConfig(current);+ if (!config.enabled || config.invalid) return errorToolResult('Agent context is disabled or invalid.');++ const tool = AGENT_CONTEXT_TOOL_REGISTRY.find((candidate) => candidate.name === name);+ if (!tool || !TOOL_HANDLERS[name]) return errorToolResult(`Unknown tool: ${cap(name, 120)}`);+ if (tool.requiredScope && !config.scopes.includes(tool.requiredScope)) {+ return errorToolResult(`Tool requires the ${tool.requiredScope} scope.`);+ }++ const parsed = tool.inputSchema.safeParse(args ?? {});+ if (!parsed.success) {+ const paths = parsed.error.issues.map((issue) => issue.path.join('.') || 'input').join(', ');+ return errorToolResult(`Invalid tool input at: ${paths}`);+ }++ return Promise.resolve(TOOL_HANDLERS[name](parsed.data, config))+ .then((output) => successToolResult(tool.outputSchema.parse(output)))+ .catch(() => errorToolResult('Context source unavailable for this request.'));+}diff --git a/server/services/agentContextMcp.test.js b/server/services/agentContextMcp.test.jsnew file mode 100644index 0000000000..2ea700fed9--- /dev/null+++ b/server/services/agentContextMcp.test.js@@ -0,0 +1,132 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ settings: {},+ getBrainProjections: vi.fn(),+ listContexts: vi.fn(),+ previewLegacyExport: vi.fn(),+}));++vi.mock('./settings.js', () => ({ getSettings: vi.fn(async () => mocks.settings) }));+vi.mock('./brainSearchIndex.js', () => ({+ BRAIN_SEARCH_TYPES: ['projects'],+ getBrainProjections: mocks.getBrainProjections,+}));+vi.mock('./workspaceContext.js', () => ({ listContexts: mocks.listContexts }));+vi.mock('./legacyExport.js', () => ({+ previewLegacyExport: mocks.previewLegacyExport,+ redactSecrets: (text) => text.replace(/sk-[A-Za-z0-9_-]{20,}/g, '[REDACTED]'),+}));+vi.mock('../lib/navManifest.js', () => ({+ NAV_COMMANDS: [{ id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['home'], keywords: ['overview'] }],+ resolveNavCommand: (query) => query.toLowerCase().includes('home')+ ? { path: '/', matched: 'home', command: { id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['home'] } }+ : null,+}));++import { AGENT_CONTEXT_LIMITS } from '../lib/agentContextValidation.js';+import {+ callAgentContextTool,+ getAgentContextManifest,+ redactAgentContextText,+} from './agentContextMcp.js';++describe('agentContextMcp service', () => {+ beforeEach(() => {+ mocks.settings = {};+ vi.clearAllMocks();+ mocks.listContexts.mockResolvedValue([]);+ mocks.getBrainProjections.mockResolvedValue([]);+ mocks.previewLegacyExport.mockResolvedValue({ sections: {} });+ });++ it('fails closed to a disabled metadata-only default manifest', async () => {+ const manifest = await getAgentContextManifest();+ expect(manifest.enabled).toBe(false);+ expect(manifest.profile).toBe('metadata');+ expect(manifest.scopes).toEqual(['navigation', 'workspaces']);+ expect(manifest.transport).toMatchObject({ loopbackOnly: true, stateful: false });+ expect(manifest.exclusions.join(' ')).toMatch(/Privacy Vault/);+ });++ it('does not execute tools while disabled', async () => {+ const result = await callAgentContextTool('list_context', { scope: 'navigation' });+ expect(result.isError).toBe(true);+ expect(mocks.listContexts).not.toHaveBeenCalled();+ });++ it('metadata profile can match private workspace text without returning it', async () => {+ mocks.settings = { agentContext: { enabled: true, profile: 'metadata', scopes: ['workspaces'] } };+ mocks.listContexts.mockResolvedValue([{+ appId: 'private-project',+ appName: 'Secret Project',+ repoPath: '/home/alice/private-project',+ savedBranch: 'private-plan',+ taskCount: 2,+ }]);+ const result = await callAgentContextTool('search_context', { query: 'Secret' });+ expect(result.isError).toBeUndefined();+ expect(result.structuredContent.items[0]).toMatchObject({ title: 'Workspace', summary: 'Active workspace with 2 task(s).' });+ expect(JSON.stringify(result)).not.toContain('Secret Project');+ expect(JSON.stringify(result)).not.toContain('/home/alice');+ expect(JSON.stringify(result)).not.toContain('private-plan');+ });++ it('redacts high-confidence personal data in explicitly enabled summaries', async () => {+ mocks.settings = { agentContext: { enabled: true, profile: 'summary', scopes: ['brain'] } };+ mocks.getBrainProjections.mockResolvedValue([{+ id: 'project-1',+ title: 'Contact [email protected] from /Users/alice/notes',+ description: 'Host 192.0.2.10 token sk-12345678901234567890',+ }]);+ const result = await callAgentContextTool('list_context', { scope: 'brain' });+ const serialized = JSON.stringify(result);+ expect(serialized).toContain('[REDACTED EMAIL]');+ expect(serialized).toContain('[REDACTED IP]');+ expect(serialized).not.toContain('[email protected]');+ expect(serialized).not.toContain('/Users/alice');+ expect(serialized).not.toContain('sk-12345678901234567890');+ });++ it('rejects reads outside configured scopes', async () => {+ mocks.settings = { agentContext: { enabled: true, scopes: ['navigation'] } };+ const result = await callAgentContextTool('list_context', { scope: 'brain' });+ expect(result.isError).toBe(true);+ expect(mocks.getBrainProjections).not.toHaveBeenCalled();+ });++ it('bounds result count and makes source failures explicit', async () => {+ mocks.settings = { agentContext: { enabled: true, scopes: ['workspaces'] } };+ mocks.listContexts.mockResolvedValue(Array.from({ length: AGENT_CONTEXT_LIMITS.maxSourceItems + 1 }, (_, index) => ({+ appId: `app-${index}`,+ appName: `Example ${index}`,+ taskCount: index,+ })));+ const bounded = await callAgentContextTool('list_context', { scope: 'workspaces', limit: AGENT_CONTEXT_LIMITS.maxResults });+ expect(bounded.structuredContent.items).toHaveLength(AGENT_CONTEXT_LIMITS.maxResults);+ expect(bounded.structuredContent.truncated).toBe(true);+ expect(bounded.structuredContent.sourceTruncated).toBe(true);++ mocks.listContexts.mockRejectedValue(new Error('catalog unavailable'));+ const failed = await callAgentContextTool('list_context', { scope: 'workspaces' });+ expect(failed.isError).toBe(true);+ expect(failed.content[0].text).toBe('Context source unavailable for this request.');+ });++ it('resolves navigation and exposes identity presence metadata only', async () => {+ mocks.settings = { agentContext: { enabled: true, scopes: ['navigation', 'identity'] } };+ mocks.previewLegacyExport.mockResolvedValue({+ sections: { identity: { label: 'Identity', present: true, privateBody: 'never return this' } },+ });+ const navigation = await callAgentContextTool('resolve_navigation', { query: 'home' });+ expect(navigation.structuredContent.match).toMatchObject({ title: 'Dashboard', path: '/' });++ const identity = await callAgentContextTool('list_context', { scope: 'identity' });+ expect(identity.structuredContent.items[0].summary).toMatch(/raw records are excluded/);+ expect(JSON.stringify(identity)).not.toContain('never return this');+ });++ it('keeps redacted summaries within the advertised cap', () => {+ expect(redactAgentContextText('x'.repeat(1_000))).toHaveLength(AGENT_CONTEXT_LIMITS.maxSummaryChars);+ });+});