| field | value |
|---|---|
| status | working draft - informative companion to the technical specification |
| date | 2026-08-12 |
| applies to | context-layer/0.1-draft |
| primary audience | application architects, adapter authors, agent developers, mobile & web teams, security reviewers |
1. purpose#
this document explains how to implement the Context Layer draft with existing sources, transports, agent protocols, models, storage systems, & user interfaces.
it uses adapter compatibility as a precise term:
a system is adapter-compatible when its native objects & security metadata can be mapped to Context Layer objects without violating the core invariants.
adapter compatibility does not imply that an adapter exists in this repository, that two vendors have tested interoperability, or that the Context Layer is part of the external protocol's official specification.
the current repository is a static interactive demonstrator with synthetic data & a local presentation voice server. the profiles below define a target for implementation.
2. where the Context Layer fits#
the Context Layer should be implemented as a control & representation layer above existing protocols:
sources and networks
HTTP | email | files | ActivityPub | AT Protocol | Nostr | Matrix | devices
|
v
capture adapters -> normalize -> extract -> user-controlled vault
|
v
ContextRequest -> policy -> semantic/discovery proxy -> ScopedContextBundle
|
v
MCP tools/resources | A2A tasks | models | workflows | web/iOS/voice UI
|
v
receipts + proposed memory updates
existing protocols remain authoritative for transport, native identity, signatures, federation, & domain behavior. the Context Layer adds a user-owned decision about what private context may cross into those systems.
3. deployment profiles#
3.1 personal local-first profile#
audience: an individual using local agents & selected cloud services.
topology:
- vault, policy engine, semantic proxy, & receipt store run on a trusted personal device or private home service.
- source adapters ingest selected local files, browser events, mail, calendars, or messages.
- local agents connect through process-local IPC or authenticated loopback endpoints.
- cloud model requests receive short-lived scoped bundles.
- writeback requires approval by default.
required controls:
- operating-system credential storage
- encrypted vault at rest
- loopback-only local HTTP by default
- per-client or per-launch authorization
- explicit source onboarding
- clear bundle & writeback approval surfaces
- backup & recovery separate from application caches
this is the recommended first implementation profile because it keeps the trust boundary small & testable.
3.2 organization or team profile#
audience: a company or team that needs shared project context with individual & organizational boundaries.
topology:
- separate personal, team, & organization-owned subjects & vault partitions
- central identity & authorization with purpose-aware policy
- shared receipt service with independent access policy
- remote agents & tools connected through authenticated gateways
- administrative policy layered beneath, not silently replacing, user or data-owner consent where required
additional requirements:
- tenant isolation
- delegation & revocation
- service identities & workload authentication
- data-region & retention policy
- administrative & user-visible receipts
- export, legal hold, deletion, & incident response procedures
- policy simulation before deployment
3.3 federated discovery profile#
audience: marketplaces, social discovery, opportunity matching, community recommendations, or cross-organization agent discovery.
topology:
- external systems submit narrow discovery requests.
- a discovery proxy evaluates requests inside the subject's private boundary.
- results use minimum reveal & expiring contact routes.
- higher-detail exchange requires a second policy decision & often user approval.
additional requirements:
- strong requester identity or explicit anonymous classification
- semantic query budgets & coordinated-probe detection
- response uniformity where negative results could leak private attributes
- abuse reporting & requester revocation
- receipts for queries & reveals
- a clear distinction between public profile data & private match features
4. compatibility matrix#
| system or category | Context Layer role | mapping | current repository state | primary caveat |
|---|---|---|---|---|
| HTTP + TLS | network binding | carry requests, bundles, receipts, & adapter traffic over authenticated HTTPS | linked as official references; no complete Context Layer API | HTTP transports data but does not supply purpose policy |
| source adapter & action target | message becomes source_event; draft/send are separate capabilities | synthetic email flow only | mailbox access is broader than permission to disclose every message | |
| files & browser clips | source adapters | file metadata & content references become source events | synthetic examples only | preserve origin, MIME type, path privacy, & integrity |
| audio & voice notes | source adapter | media reference plus transcript & confidence | synthetic examples; separate realtime voice presentation demo | transcript is derived data & must retain media provenance |
| ActivityPub | social source & outbound adapter | activitystreams object & delivery metadata map to source/provenance; outbound posts require action policy | reference link only | federated content is untrusted input & HTML must be sanitized |
| AT Protocol | social source & outbound adapter | DID, repo record, CID, lexicon type, & verification map to source/provenance | reference link only | public repositories differ from a private vault |
| Nostr | signed-event source & discovery channel | event ID, pubkey, kind, tags, signature, & relay sightings map to source/provenance | reference link & discovery illustration only | relay visibility & key custody require separate policy |
| Matrix | messaging source & action adapter | event ID, room, sender, origin timestamp, state relation, & auth context map to source/provenance | reference link only | room history & encryption state must not be flattened away |
| IPFS | content-addressed reference & artifact transport | CID may identify encrypted/public bundle artifacts or receipt batches | reference link only | public IPFS does not make unencrypted content private |
| MCP | agent-to-tool/resource bridge | approved bundles exposed as resources; context requests & actions exposed as tools | bundle mentions MCP manifests; no production server | MCP authorization does not replace Context Layer purpose policy |
| A2A | agent-to-agent task transport | bundle carried as structured task data or artifact; remote agent bound as recipient | reference link only | remote agent retention & onward disclosure must be explicit |
| local/cloud models | context consumers | prompt or model input assembled only from a scoped bundle | illustrative runtime references | provider retention & logging remain part of recipient policy |
| OpenAI Realtime | voice or multimodal consumer | WebRTC session receives scoped instructions & context through a backend | public site uses browser speech controls; no vault access | standard API keys must remain server-side & the demo differs from hardened production infrastructure |
| web UI | approval & consumption surface | show bundle provenance, permissions, expiry, actions, & receipts | multiple static interactive demos exist | static demos do not enforce policy |
| iOS/mobile | approval & consumption surface | native app consumes bundles & short-lived sessions; credentials use platform storage | not implemented | never embed provider API keys in an app binary |
| x402 | optional payment condition | request or action can reference a payment requirement & payment receipt | reference link only | payment does not grant context permission |
5. generic adapter contract#
every adapter should have an adapter manifest:
{
"adapter_id": "com.example.context-layer.matrix",
"adapter_version": "0.1.0",
"native_protocol": "matrix",
"native_protocol_versions": ["v1.x"],
"directions": ["capture", "action"],
"object_mappings": ["source_event", "receipt"],
"auth_profile": "oauth2-or-access-token",
"preserves": [
"event_id",
"room_id",
"sender",
"origin_server_ts",
"relation",
"encryption_state"
],
"lossy_fields": [],
"test_fixtures": "fixtures/matrix/"
}
5.1 capture requirements#
an inbound adapter MUST:
- verify native signatures or authentication when the native protocol supports them.
- record verification outcome separately from source content.
- preserve a native identifier or its collision-resistant digest.
- preserve source, capture, edit, & deletion times.
- preserve visibility & audience semantics.
- classify external content as untrusted data.
- store raw payload inside the vault or an approved encrypted object store.
- emit a source event referencing that payload.
- document fields lost during normalization.
- avoid triggering outbound actions during capture.
5.2 action requirements#
an outbound adapter MUST:
- receive a valid scoped bundle addressed to its runtime.
- enforce the exact allowed action.
- obtain step-up approval for side effects when required.
- avoid substituting broader native credentials for narrower bundle permissions.
- record the native transaction identifier & outcome.
- write the required receipt before reporting final success.
- return any new observations as proposals, not direct vault mutations.
5.3 edit & deletion behavior#
adapters MUST document whether the native system supports edits, redactions, deletions, tombstones, or immutable events. a normalized event MUST NOT be silently rewritten when a native record changes. the adapter SHOULD append a new event or version that references the prior record.
6. source profiles#
6.1 HTTP apis & webhooks#
HTTP is the default transport for many adapters.
recommended mapping:
- target URI & method -> source operation metadata
- authenticated principal -> source actor
- provider event ID or idempotency key -> native identifier
Date& provider timestamps -> source time fieldsETag, digest, or signature -> integrity metadata- content type -> payload media type
- response status -> capture or action outcome
webhook endpoints MUST validate provider signatures where available, enforce content limits, reject replay, & rate-limit before parsing expensive content. server-side request forgery defenses are required when captured payloads contain fetchable urls.
6.2 email#
email capture should preserve:
- message-ID & thread references
- envelope sender & recipient separately from display headers
- original date & received-chain metadata
- MIME structure & attachments
- authentication results when available
- account & folder source
- user-applied labels
an agent capability such as email.create_draft is distinct from email.send. a bundle granting draft creation MUST NOT authorize send, forward, mailbox search, or attachment access unless listed separately.
6.3 files & local workspace data#
file adapters should preserve:
- stable file identity where the platform provides one
- original path as a vault-private field
- file name, media type, size, modification time, & digest
- source repository or workspace
- version-control commit when applicable
- access-control context
bundles should expose an opaque file handle, excerpt, derived claim, or approved copy rather than an unrestricted local path. a consumer must not use path traversal or symlink resolution to escape the granted workspace.
6.4 audio & transcripts#
audio should be modeled as a media source event. a transcript is a derived artifact with:
- model or service identifier
- language
- timing segments when available
- confidence
- speaker-attribution status
- link to the source media
- redaction state
transcript text MUST NOT be represented as direct human assertion when it was produced by automatic speech recognition.
6.5 ActivityPub#
ActivityPub defines client-to-server & server-to-server social activity using activitystreams 2.0.
mapping guidance:
- activity or object
id-> native identifier actor-> source actorpublished,updated-> source timesto,cc,bto,bcc,audience-> native visibility metadata- activity type -> source event type
- object content -> untrusted payload
- delivery inbox/outbox -> source route
adapters MUST sanitize active content, preserve audience semantics, handle recursive objects defensively, & rate-limit federation traffic. a public ActivityPub object is evidence from an external source, not automatically a trusted claim.
6.6 AT Protocol#
AT Protocol provides DID-based identity, self-authenticating repositories, content-addressed records, XRPC, & lexicon schemas.
mapping guidance:
- DID -> native principal
- handle -> mutable display identifier, not the stable identity
- record URI & CID -> native object identity & integrity
- lexicon NSID -> source schema type
- repository commit & signature verification -> provenance
- firehose or subscription sequence -> capture ordering
AT Protocol repositories contain public account records. they should be treated as a source or publication target, not as storage for raw private vault content. Context Layer extensions for AT Protocol should use properly governed lexicons rather than inventing conflicting fields.
6.7 Nostr#
NIP-01 defines signed Nostr events distributed through relays.
mapping guidance:
- event
id-> native identifier & content digest pubkey-> source principalcreated_at-> source timekind-> native event typetags-> typed native metadatasig& verification outcome -> integrity metadata- relay URL & first-seen time -> provenance sighting
one event received from several relays should normally become one canonical source event with several relay sightings, not several independent facts. deletion requests are protocol events & do not guarantee that every relay removed prior content.
private context MUST NOT be published to public relays by default. key custody & signing approval remain separate action-policy concerns.
6.8 Matrix#
the Matrix client-server API uses JSON over HTTP for clients to send events & synchronize room history.
mapping guidance:
event_id-> native identifierroom_id-> native context containersender-> source actororigin_server_ts-> source time- event
type& state key -> native schema & state identity - relation metadata -> edit, reply, thread, or replacement relationship
- encryption & decryption status -> source trust metadata
adapters MUST preserve room visibility, membership context, encryption state, redaction, & replacement relationships. a decrypted event remains private according to room & user policy; decryption differs from permission to forward it to a model.
6.9 IPFS & content-addressed storage#
IPFS identifies content by CID & can transport content-addressed files or dags.
safe Context Layer uses include:
- public schema documents
- encrypted bundle artifacts where key distribution is separately controlled
- content digests for exported receipt batches
- public conformance fixtures
- portable non-sensitive documentation
unsafe default uses include:
- raw private source events
- unencrypted context bundles
- direct personal identifiers
- secrets or capability tokens
- sensitive receipt logs
IPFS privacy documentation notes that public network metadata & unencrypted content can be exposed. a CID verifies content identity; it does not create confidentiality, authorization, deletion, or guaranteed persistence.
7. agent & model profiles#
7.1 Model Context Protocol#
MCP standardizes connections between AI hosts & resources, prompts, & tools.
recommended mapping:
| Context Layer concept | MCP representation |
|---|---|
| approved bundle | read-only MCP resource with expiring authorization, or structured tool result |
| context request | MCP tool such as request_context with a narrow JSON schema |
| user approval | host-controlled elicitation or separate approval surface |
| action capability | separate MCP tool with explicit input schema & scope |
| proposed writeback | tool such as propose_memory_update, never an unrestricted storage resource |
| receipt | structured tool result plus durable Context Layer receipt |
MCP servers that expose user-specific data should use its authorization framework & security guidance. Context Layer policy remains an additional resource-use decision. an OAuth token proving access to an MCP server does not by itself authorize every vault field or purpose.
the host should keep bundle facts separate from tool descriptions & untrusted resource content. tool calls must remain allowlisted by the bundle even if the model requests another tool.
7.2 Agent2Agent Protocol#
A2A defines communication & task collaboration between independent agents.
recommended mapping:
- A2A agent card -> requester or recipient capability metadata
- A2A task -> Context Layer task reference
- A2A structured datapart -> scoped bundle or bundle reference
- A2A artifact -> generated output governed by bundle action & retention policy
- A2A task status -> operation receipt input
- remote agent identity -> bundle recipient
the bundle should be encrypted for & bound to the intended remote agent or trusted gateway. a remote agent must not forward bundle contents to sub-agents or tools unless onward disclosure & those recipients are granted.
A2A & MCP are complementary: A2A connects agents to agents; MCP connects AI hosts to tools & resources. Context Layer constrains the private context carried into either relationship.
7.3 direct model API#
for a direct local or cloud model call:
- validate the bundle.
- build the prompt from
context,instructions,capabilities, &restrictionsas separate sections. - include only approved facts & source excerpts.
- record the exact model/provider category, not a secret credential.
- apply provider retention & region behavior as recipient-policy inputs.
- restrict tool calling to bundle capabilities.
- validate model output before an external action.
- write a model-call receipt with safe digests & token or cost metadata as permitted.
- convert suggested new facts to memory proposals.
model context windows, embeddings, & vector retrieval are implementation details. they do not define authorization.
7.4 OpenAI Realtime voice profile#
the OpenAI Realtime WebRTC guide describes browser or mobile WebRTC connection setup through a developer-controlled backend or short-lived client credential.
recommended Context Layer flow:
- the UI requests a voice-capable bundle for a named task.
- policy grants the required facts, tools, duration, & audio behavior.
- a backend creates a short-lived realtime session; the standard provider key stays server-side.
- session instructions contain the bundle's approved context & restrictions.
- tool calls route through policy-aware backend handlers.
- transcripts are classified & captured only when consent & retention policy permit.
- session creation, model calls, tools, & any writeback proposals create receipts.
- the session & bundle expire together or the earlier expiry wins.
the public demonstrator uses browser speech controls & an optional server-side protocol guide. it does not connect to a production vault or provide evidence of a conforming realtime voice profile. any future realtime implementation must add public-user authentication, durable abuse controls, policy-aware tool handlers, explicit consent, & receipt behavior before deployment.
8. user interface profiles#
8.1 required authority state#
any approval or action surface should expose:
- current subject or vault
- requester & recipient
- purpose
- context categories, with sensitive categories highlighted
- allowed & denied actions
- expiration
- whether onward disclosure is allowed
- whether memory writeback is disabled, proposed, or approved
- receipt status
- provenance access appropriate to the user
interfaces must not rely on color alone for policy state.
8.2 self-assembling UI#
a bundle may include surface hints:
{
"surface_hints": {
"data_shapes": ["deadline", "people", "timeline"],
"preferred_surfaces": ["summary_card", "timeline", "draft_editor"],
"required_controls": ["provenance", "edit", "approve"],
"forbidden_controls": ["send_without_approval"]
}
}
surface hints differ from executable code. a renderer must map them to trusted components from an allowlisted design system. generated markup, scripts, & remote component urls should not be accepted from untrusted bundles.
8.3 web profile#
- keep approvals & receipts in first-class views, not hidden settings.
- use accessible focus, keyboard, & screen-reader behavior.
- avoid rendering untrusted source HTML without sanitization.
- keep secrets & standard provider credentials off the client.
- use strict content security policy & origin checks for privileged routes.
- make expiry & revoked state visible.
8.4 iOS & mobile profile#
an iOS client can act as an approval surface, context consumer, capture adapter, or local vault host.
recommended boundaries:
- store OAuth tokens & local encryption keys using platform-secure facilities.
- never embed a standard model-provider API key in the app.
- request short-lived provider sessions from an authenticated backend.
- use per-feature OS permissions & explain which source adapter needs each one.
- keep background capture opt-in, visible, & bounded.
- handle protected-data unavailability when the device is locked.
- bind local cached bundles to the app instance & expiration.
- queue receipts safely offline & fail closed for operations whose receipt is mandatory.
- expose pending memory proposals & approvals in a durable review queue.
the current repository does not include an iOS project, so this is a target profile rather than implemented behavior.
9. payments & x402#
x402 uses HTTP payment requirements for services & agents. it can compose with Context Layer in three places:
- a discovery request may require payment before expensive private matching.
- an action capability may require a payment authorization.
- a receipt may reference an external payment receipt.
the policy engine must evaluate payment & context separately:
payment satisfied != context disclosure authorized
context disclosure authorized != payment action authorized
payment credentials, wallet keys, & transaction secrets must not be included in context bundles. only minimal payment status & receipt references should cross the boundary.
10. end-to-end integration recipes#
10.1 email source to drafting agent#
- capture a native email & preserve message-ID, MIME, account, sender, recipient, & timestamp.
- extract deadline & stakeholder claims; classify a budget note as restricted.
- agent submits a request for
deadline&stakeholderwithemail.create_draft. - policy denies the budget field &
email.send. - semantic proxy emits a short bundle.
- agent generates a draft & calls the draft-only adapter.
- receipt records model call & native draft ID.
- any inferred deadline change becomes a proposal.
10.2 Nostr opportunity discovery#
- a capture adapter verifies a signed event from one or more relays.
- it records one source event & several relay sightings.
- the opportunity service submits an authenticated discovery query.
- the proxy checks query budget & evaluates private skills locally.
- it returns
possible_match& an approval-required contact route. - user approval creates a second bundle containing only the chosen contact detail.
- both the query & reveal produce receipts.
10.3 MCP tool using private project context#
- MCP host invokes
request_contextwith task, selectors, tool, & expiry. - Context Layer returns
needs_approvalor an approved bundle resource. - host makes the bundle available only to the current model turn or workflow.
- model requests an allowlisted MCP tool.
- tool handler validates the bundle capability again before side effects.
- tool output & receipt return as structured data.
- MCP server cannot resolve opaque provenance without a new request.
10.4 A2A delegation#
- local agent discovers a remote agent's capabilities.
- local policy binds the remote agent as recipient & prohibits onward disclosure.
- bundle is encrypted or delivered through a trusted gateway as structured task data.
- remote agent completes the task within listed actions.
- remote result includes task metadata; a Context Layer gateway writes the receipt.
- any follow-up requiring more context creates a new request.
10.5 voice assistant on web or iOS#
- user chooses voice mode & a task.
- UI displays which context categories & tools will be available.
- policy issues a short-lived bundle.
- backend creates a short-lived realtime session; long-lived credentials remain outside the client.
- voice model receives only approved facts & tools.
- tool actions require server-side capability checks & any step-up approval.
- transcript capture follows a separate consent & retention rule.
- session, bundle, & voice indicators end together.
11. implementation sequence#
the architecture map should not be implemented all at once. a practical sequence is:
phase 0: contract & fixtures#
- freeze draft object names & invariants.
- publish JSON schemas for request, decision, bundle, proposal, & receipt.
- create valid & invalid synthetic fixtures.
- implement deterministic schema & secret scans.
phase 1: local core#
- build one local vault with encrypted source payloads.
- implement one policy engine with explicit allow, reduce, deny, & approval states.
- implement semantic field filtering plus a simple deterministic bundle issuer.
- write append-only local receipts.
- prove raw-vault isolation in tests.
phase 2: one real source & one consumer#
- add one source adapter, preferably files or email with a narrow scope.
- add one consumer, preferably a local agent or MCP host.
- implement proposal-only writeback.
- test expiry, revocation, & receipt failure.
phase 3: discovery & remote agents#
- add query budgets & minimum-reveal responses.
- add an A2A or remote-agent profile.
- introduce recipient-bound encryption & stronger identity.
- perform privacy & abuse testing.
phase 4: UI & platform expansion#
- build consistent web & iOS approval/receipt surfaces.
- add realtime voice using short-lived sessions.
- add trusted self-assembling UI components.
- publish a cross-language conformance kit.
12. verification checklist#
architecture#
- [ ] external consumers cannot enumerate raw vault objects.
- [ ] request, decision, bundle, & receipt ids form a traceable chain.
- [ ] policy can reduce scope, not only allow or deny.
- [ ] every bundle is recipient-bound & expiring.
- [ ] proposed writeback is separated from committed memory.
adapter fidelity#
- [ ] native identifiers & security metadata are preserved.
- [ ] edits, deletions, & relay sightings have explicit mappings.
- [ ] untrusted content cannot become control instructions.
- [ ] lossy fields are documented & tested.
security#
- [ ] secrets are absent from client bundles, logs, archives, & receipts.
- [ ] local network services differ from exposed beyond their intended boundary.
- [ ] network tokens are validated for issuer, audience, expiry, & scope.
- [ ] prompt injection cannot expand capabilities.
- [ ] discovery probes are rate-limited by semantic & identity context.
- [ ] receipt preflight failure closes the operation; post-action persistence failure enters an indeterminate recovery state.
user experience#
- [ ] approval shows requester, purpose, fields, actions, recipient, & expiry.
- [ ] denied & withheld context is represented without leaking it.
- [ ] receipts are readable & searchable.
- [ ] pending memory proposals have approve, reject, & inspect-source paths.
- [ ] voice & background capture states are continuously visible.
operations#
- [ ] key rotation, backup, recovery, revocation, & deletion are documented.
- [ ] conformance fixtures run deterministically.
- [ ] version migrations are tested before policy or schema rollout.
- [ ] incident response can identify affected bundles & recipients from receipts.
13. known limitations & research areas#
- semantic redaction is probabilistic & can leak indirect identifiers.
- provenance does not guarantee source truth.
- signed receipts attest to reported operations, not complete behavioral correctness.
- recipient deletion & retention may be impossible to enforce after disclosure without trusted hardware or legal controls.
- minimum-reveal matching remains vulnerable to inference without durable query accounting.
- cross-device user ownership requires difficult recovery & delegation choices.
- policy language can become too complex for users to understand.
- self-assembling interfaces can obscure authority unless constrained to trusted components.
- interoperability requires governance, registered schemas, test suites, & multiple independent implementations.
these limitations are part of the protocol design problem, not reasons to hide the boundary behind a generic 'AI memory' feature.