Security & Governance¶
Where it stands (8 November 2026): Part B is the policy engine as built (RM-36: DEC-90, DEC-91, DEC-134 to DEC-138). The complete audit log is DEC-92 (RM-34). The Secrets Vault (Part C) isn't built, and Parts A, C and D are still April's design (tech debt R7); the architecture briefing has the detail.
Precis¶
This document is the canonical reference for how Thinklio keeps data safe, controls what agents can do, and manages the credentials agents need to work with external systems. It consolidates the April 2026 security model, secrets vault specification, governance policy framework, and MCP credential and permission model into one layered reference.
Thinklio enforces security in depth across four layers: network, application, database, and cache. Tenant isolation is structural rather than policy-only: code bugs should not expose one account's data to another. Every authentication attempt, every authorisation decision, and every data access is logged. Agent-to-agent delegation can only narrow permissions, never widen them.
Authentication is delegated to Clerk (the Thinklio default, replacing the earlier Supabase Auth design). Clerk handles email, OAuth, magic links, and session lifecycle; the Convex backend validates Clerk tokens via a first-class integration. The three external API surfaces (Channel API, Platform API, Integration API) each have their own authentication mechanism but resolve to the same platform identity and authorisation model.
Authorisation is evaluated at four levels: platform (can this user access this resource?), agent (can this agent perform this action?), assignment (is this action further restricted for this context?), and step (can this specific step execute right now given budget, rate limits, delegation depth, and approval gates?). The evaluation order is: account policies, assignment restrictions, trust level, budget, rate limit, delegation depth and cycle checks, approval gate. Fail-closed behaviour applies: if the policy engine cannot evaluate, the decision is deny.
The governance policy framework provides eight categories of declarative, data-driven rules: action permissions, cost limits, data boundaries, temporal constraints, delegation constraints, content policies, audit requirements, and approval gates. Policies layer as account, team, and user, with the most restrictive wins rule. Every policy carries scoping fields (agent, channel, tool, user) so a rule can target exactly the right context. Industry template packs for healthcare, finance, and legal layer atop a safe default baseline and can be applied during onboarding.
Credentials are stored and injected through three connected mechanisms. Platform secrets (LLM keys, internal service tokens) live in infrastructure secret management and are managed by Thinklio ops. User- and account-facing secrets live in the Secrets Vault, which is a first-class product feature: users store passwords, API keys, TOTP seeds, and configuration blocks with fine-grained sharing, access logs, and agent integration. Agents can use stored credentials only with per-secret, per-session user approval; values are never stored in message history, reasoning traces, or knowledge extraction. MCP servers receive credentials per-request as HTTP headers (never stored on the server); Thinklio handles OAuth refresh cycles and surfaces user-friendly errors when credentials are missing or invalid.
MCP tool permissions enforce a core principle: in any channel, an agent's effective tool set is the intersection of all human participants' tool permissions. This prevents privilege escalation via shared channels. Tool access is granted at three levels (organisation, team, user) with most-restrictive-wins resolution and a max-of-teams rule for multi-team users. In group chats, tools downgrade to the lowest common permission level; if a participant has no access, the tool becomes invisible to the agent. Agents in channels have four visibility states: active, limited, unavailable, and needs-setup. Delegation chains preserve the intersection rule at every level. Tool calls use the credentials of the user who triggered the request for user-scoped integrations; account-scoped credentials use the shared token, and access control is handled by Thinklio's permission layer rather than the external system.
The remainder of this document is structured in four parts. Part A covers the platform security model (threat model, authentication, authorisation, data isolation, input validation, rate limits, logging, incident response, compliance). Part B is the policy engine as built (the rules, the decision, approvals, spending limits, operating hours and content rules). Part C covers credential management (the full Secrets Vault specification plus MCP credential injection and OAuth handling). Part D covers MCP tool permissions (grants, effective resolution, channel downgrade, delegation chains, and the MCP metadata endpoint). For data ownership and scoping see 04-data-model.md. For the harness that invokes policies see 03-agent-architecture.md. For Convex helpers used in enforcement (customQuery, customMutation, RLS, triggers) see 11-convex-reference.md.
Table of contents¶
- Part A: Security model
- 1. Security principles
- 2. Threat model
- 3. Authentication
- 4. Authorisation
- 5. Data isolation
- 6. Input validation
- 7. Rate limiting
- 8. Security logging and monitoring
- 9. Incident response
- 10. Compliance
- Part B: Governance policy framework
- 1. What it decides
- 2. The rules
- 3. The decision
- 4. Approvals
- 5. Spending limits
- 6. Operating hours and content rules
- 7. Where it's managed
- 8. Not yet
- Part C: Credential management
- 1. Overview and credential scopes
- 2. Secrets Vault specification
- 3. MCP credential injection
- Part D: MCP tool permissions
- 1. Core principle
- 2. Permission grants
- 3. Resolving a user's effective tool set
- 4. Channel tool resolution
- 5. Agent visibility states
- 6. Delegation chains
- 7. Whose credentials are used
- 8. MCP server metadata endpoint
- 9. Integration lifecycle
- 10. Summary
- References
- Revision history
Part A: Security model¶
1. Security principles¶
- Defence in depth. Security is enforced at multiple layers: network, application, database, and cache. No single layer's failure compromises the system.
- Least privilege. Every entity (user, agent, service) has the minimum permissions needed to function.
- Fail closed. If a security check cannot be performed (service down, timeout), the action is denied.
- Audit everything. Every authentication, authorisation decision, and data access is logged.
- Isolation is structural. Tenant data isolation is enforced by architecture, not just policy. A code bug should not expose one tenant's data to another.
- Delegation does not escalate. Agent-to-agent delegation can only narrow permissions, never widen them. A delegate agent operates under the intersection of its own permissions and the invoking context's restrictions.
2. Threat model¶
2.1 Assets¶
| Asset | Sensitivity | Examples |
|---|---|---|
| User chats | High | Message content, personal context |
| Knowledge facts | High | Extracted information about users, teams, accounts |
| Agent configuration | Medium | System prompts, tool access, policies |
| Credentials | Critical | API keys, auth tokens, database passwords |
| Operational data | Medium | Usage metrics, cost data, system configuration |
| Audit logs | High | Security events, access records |
| Job data | High | Dispatch payloads, context bundles, subjob results |
| Delegation chains | Medium | Agent composition structure, invocation contracts |
2.2 Threat actors¶
| Actor | Capability | Motivation |
|---|---|---|
| External attacker | Network access, public endpoints | Data theft, service disruption |
| Malicious user | Authenticated access, legitimate account | Privilege escalation, data access |
| Compromised agent | Agent-level permissions | Data exfiltration via tool abuse |
| Malicious delegate agent | Delegated permissions | Exploiting delegation chain to access data or tools beyond intended scope |
| Insider (compromised admin) | Administrative access | Data theft, sabotage |
| Supply chain | Compromised dependencies/images | Backdoor, cryptomining |
| Malicious external tool | Integration API registration | Data exfiltration via tool responses, prompt injection via tool output |
2.3 Attack vectors¶
- Authentication bypass: gaining access without valid credentials
- Privilege escalation: accessing resources beyond assigned permissions
- Cross-tenant data access: reading another account/team/user's data
- Prompt injection: manipulating agent behaviour through crafted inputs
- Tool abuse: using agent tool access for unintended purposes
- Delegation escalation: using agent composition to bypass permission restrictions
- Resource exhaustion: overwhelming the system to cause denial of service
- Credential theft: stealing API keys, tokens, or database credentials
- Data exfiltration: extracting sensitive data through legitimate channels
- External tool injection: dynamically registered tools returning malicious content to influence agent reasoning
3. Authentication¶
3.1 Clerk integration (Thinklio default)¶
User authentication is handled by Clerk. Clerk manages email/password, magic link, and OAuth (Google, GitHub, etc.) authentication flows, and provides organisation and role primitives that map directly to Thinklio accounts and RBAC. The Convex backend never handles raw credentials: all credential management is delegated to Clerk.
Clerk tokens are validated inside Convex query, mutation, and action functions via the first-class Clerk integration (see 11-convex-reference.md section 8). Identity is resolved from the token; organisation membership, roles, and permissions are resolved from Convex tables (account_user, team_member, agent_assignment) keyed by the Clerk user ID, not from token claims.
3.2 External authentication: three API surfaces¶
Users and systems authenticate through the gateway and HTTP action endpoints. The three API surfaces have different authentication mechanisms, all resolving to the same platform identity and authorisation model.
Channel API: authenticates as a user.
- The external system provides credentials that map to a platform user identity
- All interactions are governed by that user's permissions, team memberships, and account policies
- Supported methods: Clerk session token (JWT), API key scoped to a user context
Platform API: authenticates as an account or service account.
- API keys scoped to specific accounts, teams, or agents
- Operations governed by the role associated with the API key (admin, member, etc.)
- Supported methods: API key with account/team scope
Integration API: authenticates as an external system.
- Registration requires account approval
- Execution credentials scoped to specific tool definitions
- Thinklio-to-external calls carry authentication configured at registration time
- External-to-Thinklio calls authenticate via API key with tool-specific scoping
3.3 JWT structure¶
Clerk produces a standard JWT (its convex template). Since RM-7's release 2 (4 November 2026) it says only who the person is; the claims Convex uses are:
{
"sub": "user_2abc123...",
"email": "user@example.com",
"email_verified": true,
"aud": "convex",
"exp": 1710000000,
"iat": 1709913600
}
Which organisation and with what role is Thinklio's own decision, on every call (packages/backend/convex/lib/accountResolve.ts, used by every account-scoped function through lib/middleware.ts): the person's chosen organisation is user_profiles.selectedAccountId, and their role is their row in account_members. Any organisation claims a token still carries are ignored. With no organisation chosen, or after they've been removed, the answer is "Choose an account". The verified email is used once more: to accept invitations waiting for that address (members.acceptMine).
3.4 Channel authentication¶
Each channel adapter handles authentication in its native way:
- Telegram: user ID verification against registered users
- Channel API: bearer token (Clerk JWT or API key)
- Web chat: Clerk session token from the web app
Channel authentication maps to platform identity. A Telegram user ID is linked to a platform user account.
3.5 Inter-service authentication¶
During the Convex-first phase, server functions run inside Convex and share trust via the managed runtime. Internal functions (see 11-convex-reference.md section 4) are only callable from other Convex functions, not from clients. For external calls out (to HTTP endpoints, MCP servers, LLM providers), the action function authenticates with service tokens stored in platform secrets (section C.1) or per-account credentials resolved from the vault (section C.2).
3.6 Session management¶
- Clerk session tokens with configurable expiry
- Refresh token rotation handled by Clerk
- Session state maintained by Clerk; Convex queries are reactive and re-run when auth changes
- Explicit logout invalidates the Clerk session
- Concurrent session limits configurable per account via Clerk
4. Authorisation¶
4.1 Permission model¶
Authorisation is evaluated at four levels:
1. Platform level: can this user/system access this resource at all?
User → AccountUser (role) → Account
User → TeamMember (role) → Team
User → AgentAssignment → Agent
API Key → Scoped account/team/agent access
2. Agent level: can this agent perform this action?
Agent → AgentTool (permission) → Tool
Agent → capability_level → action type
Agent → Account.policies → governance rules
3. Assignment level: is this action further restricted for this context?
4. Step level: can this specific step execute right now?
Step → PolicyEngine → trust level check
Step → AssignmentRestrictions → tool restriction check
Step → BudgetEnforcer → cost check
Step → RateLimiter → rate check
Step → DelegationRules → depth and cycle check
4.2 Role-based access control¶
Thinklio has three levels (DEC-61): the organisation, which is the tenant and contains everybody (the account in the code, with billing); teams, groups of two or more of its people, where a person can be in several; and individuals. Roles are held in Thinklio's own tables, and Clerk only signs people in (DEC-57; RM-7, plan docs/plans/2026-11-03-accounts-and-members.md). Admins invite people by email, change roles and remove people in Settings › Organisation › People and teams (DEC-62); every change is in the audit log.
| Role | Scope | Capabilities |
|---|---|---|
| App admin | Across organisations | Novansa staff: the model registry, feedback and platform settings. Set by hand from the backend (platformAdmins:grant), never from the app (DEC-59) |
| Owner | Organisation | Everything an admin can do, plus deleting the organisation and billing. One per organisation: its creator, who passes ownership to an admin before they can leave (DEC-60) |
| Admin | Organisation | People, teams, agents, policies and settings |
| Member | Organisation | Works in the organisation: spaces, chats, tasks, agents |
| Read only | Organisation | Sees what a member sees and changes nothing shared. Their own personal space stays theirs |
| Team lead, team member | Team | Membership of a team: it opens the team's spaces (the lead as their Owner) and brings its knowledge there (team_members.role) |
| Space owner, member, commenter, viewer | Space | What someone can do in a space they can open (lib/spaces.ts); the viewer is shown as Read only |
Who can open a space follows its owner (RM-37, DEC-84, DEC-139): every space belongs to the organisation (everyone in it can open it), a team (its people and the organisation's admins) or a person (their personal space). Someone's role there is the one the space's member list gives them, else Owner for an admin or the team's lead, else Member; Read only in the organisation caps it. A member-list row for someone the owner doesn't include gives them nothing. Admins move a space between the organisation and a team (spaces.setOwner), which removes the rows of people the new owner doesn't include; a team that owns spaces can't be removed until they move. Setting up an organisation offers team templates, each making the team (with the admin as lead) and a space of its own (DEC-85, DEC-140).
Read only is defined but not yet given to anyone: its writes are refused everywhere first (RM-7 release 2c), and until then People offers Admin and Member. Guests from outside the organisation, given a space or a chat as read only, comment or edit, are an idea for later (IDEA-40).
4.3 Policy engine¶
The policy engine evaluates every tool execution, delegation, and sensitive operation. Policies are defined at account, team, and user levels and enforced by the harness. The full policy framework is Part B of this document.
Policy evaluation order:
- Account policies: explicit allow/deny rules, delegation limits
- Assignment restrictions: per-assignment tool narrowing
- Trust level check: does the user's trust level meet the tool's requirements?
- Budget check: is there sufficient budget for this operation?
- Rate limit check: has the user/agent exceeded rate limits?
- Delegation checks: depth limit, cycle detection (for agent-type tools)
- Approval check: does this action require explicit approval?
Policy decisions:
allow: proceed with executiondeny: block with reason loggedrequire_approval: pause and request human approval
Fail-closed behaviour: If the policy engine cannot evaluate (service unavailable, timeout), the decision is deny.
4.4 Trust levels¶
Superseded for agents (DEC-152, 11 November 2026): agents have no trust level. What an agent may do is its own capability list, and how carefully is the policy engine's level (Part B). This section is the older design.
Trust is graduated and governs tool access:
| Trust Level | Description | Example Tools |
|---|---|---|
read |
Read-only operations | Search web, get weather, read documents |
low_risk_write |
Write operations with limited impact | Create todo, send notification, update note |
high_risk_write |
Write operations with significant impact | Send email, modify database, execute payment |
Users are assigned trust levels per agent assignment. Agents are configured with tool trust requirements. The policy engine compares user trust against tool requirements.
The policy engine (Part B) extends this with a five-level permission scheme (deny, read, draft, confirm, autonomous) that applies to specific actions rather than coarse tool categories.
4.5 Per-assignment tool restrictions¶
Each agent assignment can include tool_restrictions that narrow the agent's configured tool permissions for that specific context. This applies to both regular tools and agent-as-tool delegations.
Key principles:
- Restrictions can only narrow, never widen. An assignment cannot grant tool access the agent doesn't already have.
- An account policy cannot grant permissions that the assignment has removed.
- For agent-as-tool delegations, assignment restrictions can limit what actions the delegate is asked to perform.
- The same agent assigned to different teams can have different effective tool permissions via different assignment restrictions.
4.6 Delegation security¶
Depth limits. The account policy max_delegation_depth (default: 3) limits how many levels of agent-to-agent delegation are permitted. The policy engine denies act steps that would exceed this depth.
Cycle detection: configuration time. When an agent-as-tool is registered in Agent Studio, the system checks the delegation graph for cycles. Circular configurations (A → B → C → A) are rejected.
Cycle detection: runtime. Each delegation carries a delegation chain (list of agent IDs in the current call stack). If a delegation would invoke an agent already in the chain, the policy engine denies it. This catches cases that configuration-time checks might miss (e.g., if the delegation graph was modified after configuration).
Permission narrowing through delegation. When Agent A delegates to Agent B, Agent B operates under:
- Its own configured tool permissions (maximum capability)
- Narrowed by the assignment restrictions for the context Agent A is operating in
- Narrowed by account policies
The delegate never gains permissions the invoking agent doesn't have in its current context.
Context isolation. The delegate does not receive the invoking agent's full context, knowledge layers, or chat history. It receives the invocation payload (conforming to the parameter schema) and assembles its own context from its own knowledge layers scoped to its own assignment.
5. Data isolation¶
5.1 Database level¶
Application-layer authorisation (implemented with convex-helpers row-level security; see 11-convex-reference.md section 9) enforces that queries only return data the current user is authorised to see:
- Knowledge facts: scope-based access (everyone has the organisation's; an agent uses a person's own only when talking to them alone, and a team's in that team's chat; nobody gets another person's personal knowledge; DEC-61, DEC-63 and doc 03 § 11)
- Interactions: users see only their own interactions
- Jobs: visible to users who created the originating interaction or are registered observers
- Events: scoped to the user's agent assignments
- Configuration: account admins see account configuration; members see only what they need
RLS is applied as a custom function wrapper around every query and mutation:
// convex/lib/accountAuth.ts
export const accountQuery = customQuery(query, {
args: { accountId: v.id("account") },
input: async (ctx, { accountId }) => {
const identity = await ctx.auth.getUserIdentity();
if (!identity) throw new Error("Unauthenticated");
const membership = await ctx.db
.query("account_user")
.withIndex("by_account_user", q =>
q.eq("accountId", accountId).eq("userId", identity.subject))
.unique();
if (!membership) throw new Error("Not a member of this account");
return { ctx: { ...ctx, accountId, membership }, args: {} };
},
});
Every application-facing query and mutation uses accountQuery or accountMutation rather than the raw query/mutation primitives.
5.2 Note visibility model¶
Note visibility follows a layered model:
- Notes with
visibility = 'private'are visible only to the creator - Notes with
visibility = 'team'are visible to team members - Notes with
visibility = 'account'are visible to all account members - Granular sharing via
note_sharerecords can extend visibility to specific users or teams - The
note_mentionsystem tracks @ mentions within note content, triggering notifications to mentioned entities
5.3 Application level¶
Every server function that accesses data includes context validation:
export const getKnowledge = accountQuery({
args: { agentId: v.id("agent"), userId: v.string() },
handler: async (ctx, args) => {
// Verify the requesting user has access to this agent
const hasAccess = await ctx.db.query("agent_assignment")
.withIndex("by_agent_user",
q => q.eq("agentId", args.agentId).eq("userId", args.userId))
.unique();
if (!hasAccess) throw new Error("Unauthorised");
// proceed with scoped query
},
});
5.4 Cache level¶
Cache keys include scope identifiers. A cache key for user knowledge is thinklio:knowledge:agent:{agent_id}:user:{user_id}. There is no cache key that could return cross-tenant data. Active job cache keys include the job ID; job data is only accessible to authorised observers.
5.5 Network level¶
- Convex server functions run in Convex-managed infrastructure
- No custom service-to-service network to expose
- Gateway and HTTP actions are the only public-facing interfaces
- SSL/TLS for all external connections
- External service calls (LLM providers, MCP servers, third-party APIs) go through Convex actions with validated credentials
6. Input validation¶
All user input is validated before processing:
- Message content: length limits, encoding validation
- Commands: parameter validation against defined schemas
- API requests: JSON schema validation on all endpoints across all three API surfaces
- File uploads: type checking, size limits, malware scanning (future)
- Tool parameters: validated against tool parameter schemas
- Delegation invocation payloads: validated against the agent-as-tool's parameter schema
- Dynamically registered tool definitions: schema validation, endpoint reachability check
Convex server functions validate arguments via v validators on every function definition. The convex-helpers Zod integration provides richer validation where needed.
6.1 Prompt injection defence¶
User input is never directly concatenated into system prompts. Mitigation strategies:
- Clear delimiters between system instructions and user content
- Input sanitisation removing known injection patterns
- Output monitoring for anomalous responses
- Trust boundaries: user content is always treated as untrusted data
- Rate limiting to prevent brute-force injection attempts
- External tool output is treated as untrusted data in the agent's context (same as user input)
6.2 External tool security¶
Dynamically registered external tools (via Integration API) introduce additional attack surface:
- Tool registration requires account approval before the tool becomes available
- Tool responses are treated as untrusted data (cannot override system prompts or policies)
- Tool endpoints are validated at registration time
- Health monitoring detects unresponsive or misbehaving tools
- Circuit breakers prevent cascading failures from unhealthy external tools
- Rate limiting applies per tool per agent
7. Rate limiting¶
Rate limits are enforced at multiple levels. The implementation uses the Convex Rate Limiter component (see 11-convex-reference.md Part B) for transactional, sharded token bucket and fixed window enforcement.
| Level | Scope | Default Limit | Enforcement point |
|---|---|---|---|
| Gateway | Per IP | 100 req/min | Gateway edge |
| User message | Per user | 20 msg/min | Gateway |
| Tool execution | Per agent per tool | 10 exec/min | Harness |
| LLM calls | Per agent | 30 calls/min | Agent service |
| Channel API | Per API key | 60 req/min | Gateway |
| Platform API | Per API key | 60 req/min | Gateway |
| Integration API | Per tool registration | 30 exec/min | Gateway |
| Job dispatch | Per agent | 10 jobs/min | Workflow dispatcher |
Per-feature rate limits (for example, the per-user limits on secret reveal/copy in Part C) are defined in their own sections.
8. Security logging and monitoring¶
8.1 Security events¶
All security-relevant events are logged:
- Authentication attempts (success and failure) across all three API surfaces
- Authorisation decisions (especially denials)
- Policy engine evaluations
- Delegation depth and cycle check results
- Rate limit hits
- Input validation failures
- External tool registration and approval decisions
- Unusual patterns (rapid command sequences, anomalous tool usage, unexpected delegation chains)
8.2 Alerting¶
Alerts trigger on:
- Repeated authentication failures from same source
- Policy denial rate exceeding threshold
- Rate limit hits exceeding normal levels
- Service health check failures
- Unusual tool execution patterns
- Delegation depth limit hits (may indicate misconfiguration)
- External tool health failures
9. Incident response¶
- Security events aggregated in audit log
- Alert escalation to admin notification channel
- Agent kill switch for immediate containment (cancels pending jobs)
- Audit trail preserved for investigation
- Post-incident review process
10. Compliance¶
10.1 GDPR readiness¶
- Right to access: users can export all their data
- Right to erasure: users can request deletion; user data hard-deleted, contributions anonymised, job observer registrations removed
- Data portability: export in standard formats
- Consent: explicit consent for data processing
- Data minimisation: only necessary data collected
- Retention: configurable retention periods with automatic archival
10.2 Data residency¶
Initial Thinklio deployment runs on Convex's managed cloud. Data residency requirements (EU-only for some customers, AU-only for others) can be met either by Convex region selection or by the self-hosted deployment path (see 11-convex-reference.md section 12).
Part B: Governance policy framework¶
The policy engine as built (RM-36, 8 November 2026; DEC-90, DEC-91, DEC-134 to DEC-138; plan ../plans/2026-11-08-policy-engine.md). It replaced April's framework (account, team and user policy categories, templates and a resolver; in this doc's history up to version 1.1.0), of which only operating hours and content rules had ever run.
1. What it decides¶
Every capability call (RM-35's registry: capabilities/) by an agent, an API key or an MCP client is decided before it runs, in invokeCapability (capabilities/registry.ts). People's own clicks in the app keep their roles (organisation and space roles) until a rule needs them (DEC-135). Data boundaries wait for Telegram and email (DEC-138).
The levels, narrowest first: deny, read, draft, confirm, autonomous.
| Level | A read (cost class read) |
A write or a model call |
|---|---|---|
| deny | refused | refused |
| read | allowed | refused |
| draft | allowed | an approval the person can change before it's done |
| confirm | allowed | an approval to answer as prepared |
| autonomous | allowed | done |
A refusal is the capability error forbidden: a 403 from the API, an error result over MCP, and a tool result telling the model why. It's audited as denied, naming the rule.
2. The rules¶
One table, policies (lib/policyRules.ts), each row written at a level of the cascade (scope: organisation, team or person), with a typed rule:
- action: a pattern (
tasks:create,tasks:*,*:reador*), a level, optionallywho(agents or keys) and, for confirm,approver: "admins". - spending: per day and per month in USD (§ 5).
- hours: a time zone, hours per day (a day left out is closed), and what happens outside them (deny, or draft).
- content: a voice, a topic restriction, a disclaimer or a length, for every agent or one (
agentId).
An organisation's rule may name a team or a person (named), to set their level apart from everyone else's: wider or narrower. Admins write the organisation's and teams' rules; a person writes their own (actions only), which only narrow. policies.save checks each rule (patterns, time zones, hours, limits) and that a named team or person is in the organisation.
Compiled: every change rebuilds the organisation's one policy_sets row (lib/policySets.ts), so a decision reads one row and the person's teams. With no row, Thinklio's defaults apply: agents and keys act on their own (DEC-134), and spending is limited to $10 a day and $100 a month (DEC-137).
3. The decision¶
decide(rules, request) (lib/policyEngine.ts) is a pure function:
- An unknown action is refused, and so is anything when the rules can't be read: it fails closed.
- The organisation's level: its rule naming the person, else the widest of those naming one of their teams, else its rule for everyone, else the default. Among matching rules the most specific wins: the exact action, then its area, then its verb, then everything; a rule for agents or keys before one for both; on a tie, the narrowest.
- Narrowed by the team that owns the place (the space the call names, else the chat's team or its space's team; RM-37 gives spaces teams).
- Narrowed by the person's own rules. An agent acts for a person and is held to their level (DEC-91); a key acts for no one, so named and personal rules don't apply to it.
- In a group chat, what an agent reads is held to everyone present (up to 50 people).
- A cap from the context narrows last: draft outside operating hours. A delegate shares its caller's turn, and so its snapshot and cap; per-agent limits are RM-40's.
Snapshots: an agent's turn takes the rules once when it starts (policyCheck.snapshot) and decides every tool call from them (DEC-90). The API and MCP take them per call.
4. Approvals¶
A draft or confirm becomes a row in pending_approvals (approvals.ts, DEC-136): the capability and its input, who asked and for whom, why, who answers, and its state (pending, approved, declined, expired). It is the interaction protocol's action affordance (~/dev/docs/standards/interaction-protocol.md § 7): one row, shown in Waiting on you on Home (web and app) and as a card in the chat it came from, answered from either.
- Who answers: the person the agent acts for, unless the rule says the admins; a key's always go to the admins. The person is told in the app; admins are pushed and emailed.
- Approve runs the capability as the one who asked, under the original request ID (
approvalsRun.ts). The draft or confirm is satisfied, but the engine decides again, so a refusal made since stands. A draft can be changed first (on the web). - Decline records an optional note. Unanswered, it expires after seven days.
- The caller hears it waits: the agent's tool returns
waiting_for_approvalordrafted_for_review; the API answers 202 withstatus: "pending_approval"and the approval's ID; MCP returns text saying it isn't done yet. - The audit log records
approval.requested(decisionpending),approval.approved,approval.declinedandapproval.expired.
5. Spending limits¶
spending.ts (DEC-137). The organisation's limits (its rule, else $10 a day and $100 a month) and a person's own (an organisation rule naming them) are checked against usage_daily (UTC days):
- before an agent's turn, with an estimate from its model's price (6,000 tokens in, 1,000 out);
- before a capability whose cost class is model (knowledge search).
At or past a limit, the call stops, saying whose limit it is and that an admin can raise it in Settings › Organisation › Policies. After each recorded use, admins (and a person with their own limit) are told at 80% and at the limit, once a period (spending_alerts). Usage is always recorded (B21). This replaced the advisory token budget. The privacy policy's draft section on decisions made with software has a line for it (../audits/2026-11-03-automated-decisions.md).
6. Operating hours and content rules¶
From the snapshot (lib/policyHours.ts): the organisation's hours rules and those of the place's team. Outside them a turn is refused with the reason in the chat, or capped at draft, so its writes become approvals while reads go ahead. Content rules are added to the prompt by the context handler (policyCheck.contentForPrompt), matching an agent by ID (B36).
7. Where it's managed¶
- Settings › Organisation › Policies (admins): a level for each action for agents and for keys, exceptions for a person or team or for several actions, spending limits (with what's been spent), operating hours, and what agents are told.
- Settings › Profile › What agents may do for you: the person's own level for each action.
- A team's own rules are on its card in Settings › Organisation › People and teams (RM-37): what agents and keys may do in its spaces, only narrowing.
- Audit shows every decision, refusal and approval.
8. An agent's own capabilities and limits (RM-40)¶
DEC-91 as narrowed by DEC-152 and DEC-155.
- Its capabilities. An agent is offered only the capabilities ticked in its settings (
agents.capabilities).decideCallrefuses an agent anything outside its list, before the rules, so a call it wasn't given is denied and audited even if one were made. - Who it acts for. It is never more than the person it acts for, and in a group chat it is held to everyone present, as before.
- Delegates. The delegation set is the grant: a coordinator needn't hold its delegates' capabilities. A delegate acts with its own capabilities, for the same person and chat. It is decided from the turn's snapshot, so every rule that holds for the coordinator holds for it. It shares the run's request ID and budget, and goes only as deep as the first agent allows (1 by default, at most 2), never asking an agent twice.
- Run limits. Each agent has steps in one turn and a cost for one run, delegates included, on top of the organisation's and the person's spending limits (§ 5). Reaching one is audited as
agent.turn.limited.
9. Not yet¶
- Data boundaries: RM-42 (DEC-138).
- People's own clicks under the engine: when a rule needs them (DEC-135).
- Credentials (personal tokens, organisation and team keys): RM-2; each becomes a principal the engine already decides for.
Part C: Credential management¶
Part C covers how Thinklio stores, protects, and injects credentials that agents and MCP servers need to call external systems. It has three layers: a brief overview of the three credential scopes (platform, account, user) and how they map to storage; the full Secrets Vault product specification (a first-class Thinklio feature for user-managed secrets with sharing, agent integration, and access logging); and the MCP credential injection model that resolves credentials per-request and handles OAuth refresh transparently.
Note on storage backend. The original Secrets Vault specification was designed against Supabase Vault. In the Convex-first architecture, the vault is implemented on top of Convex tables using envelope encryption: values are encrypted client-side by a server action with a key held in platform secrets (or a KMS), and only ciphertext plus a vault_ref is stored in the secret table. The API surface, security properties, and data model described below are unchanged. Where the text below references vault.create_secret() or vault.decrypted_secrets, treat these as operation names rather than specific Postgres functions; the implementation binds them to the equivalent Convex actions.
1. Overview and credential scopes¶
Every external integration needs credentials to authenticate to the upstream API. Thinklio recognises three scopes:
| Scope | Who provides | Storage | Lifecycle | Example |
|---|---|---|---|---|
| Platform | Thinklio (us) | Infrastructure secrets / Convex env | Managed by Thinklio ops | OpenRouter API key, internal service tokens |
| Account | Organisation admin | Account-scoped Secrets Vault entry | Admin configures once, shared by all agents | Xero OAuth tokens, shared Notion workspace token |
| User | Individual user | User-scoped Secrets Vault entry | Each user provides their own | Cliniko API key (per-clinician), personal Notion token |
The scope an integration needs is declared in its MCP /meta endpoint (see Part D section 8). Thinklio's admin UI uses this to show the credential input in the right place: account-scoped credentials appear in Settings > Integrations (admin-only); user-scoped credentials appear in each user's personal Settings > Integrations.
Platform secrets sit outside the vault: they are loaded as environment variables on the Convex deployment or injected by the operations pipeline. The vault is exclusively for account- and user-scoped secrets.
2. Secrets Vault specification¶
The Secrets Vault is a Thinklio product feature: users store credentials, API keys, TOTP seeds, configuration blocks, and other sensitive data with fine-grained sharing, full access logging, and agent integration. Values are never displayed in the UI except via explicit reveal by the creator; shared users can only copy to clipboard. Agents can use stored credentials only with per-secret, per-session approval and every access is logged.
2.1 Vault overview and design principles¶
Thinklio's Secrets Vault provides secure storage, retrieval, and sharing of credentials, API keys, certificates, configuration blocks, and other sensitive data. It is a core data primitive alongside tasks, contacts, items, and notes.
The vault integrates with the agent system: agents can use stored credentials on the user's behalf (with explicit approval) without ever exposing values in chat history. The vault also supports secure sharing between team members with single-use and expiring options.
Design Principles¶
- Zero display by default. Secret values are never shown in the UI except via an explicit reveal action by the creator. Shared users can only copy to clipboard: the value never appears on screen.
- Values never in our tables. The
secrettable stores metadata (name, type, URL, username). The actual secret value lives in Supabase Vault, referenced byvault_ref. Even if thesecrettable is compromised, values remain encrypted. - Every access is logged. A dedicated
secret_access_logtable records every vault read with user, agent, access type, IP, and timestamp. No silent reads. - Agent access requires approval. An agent must request user approval per-secret, per-session before reading a value. Delegation does not inherit secret access.
- Sharing is controlled. Only the creator can share. Shared users cannot re-share. Shares can be single-use, time-limited, and revocable.
2.2 Vault data model¶
2.2.1 Secret¶
The metadata record for a stored secret. The actual value is in Supabase Vault.
| Field | Type | Description |
|---|---|---|
| id | UUID | PK |
| account_id | UUID | FK → account (CASCADE) |
| scope | TEXT | user, team, account |
| scope_id | UUID | Scope entity ID |
| secret_type | TEXT | password, api_key, ssh_key, certificate, config_block, secure_note, totp |
| name | TEXT | Human-readable name (e.g. "Staging DB", "AWS Production") |
| vault_ref | TEXT | Reference to the Supabase Vault entry: the ONLY link to the encrypted value |
| username | TEXT | Optional: for login credentials |
| url | TEXT | Optional: for website passwords |
| visibility | TEXT | private, team, account |
| expires_at | TIMESTAMPTZ | Optional: for rotation/expiry alerts |
| last_accessed_at | TIMESTAMPTZ | Updated on every vault read |
| last_accessed_by | UUID | FK → user_profile |
| access_count | INTEGER | Total number of vault reads |
| metadata | JSONB | Notes, tags, custom fields, rotation schedule |
| created_by | UUID | FK → user_profile |
| created_at | TIMESTAMPTZ | |
| updated_at | TIMESTAMPTZ |
Constraints:
- UNIQUE(account_id, scope, scope_id, name): no duplicate names per scope
- RLS: private secrets visible only to creator + explicit shares
Secret types:
| Type | Fields Used | Description |
|---|---|---|
password |
username + vault_ref + url | Website/service login credentials |
api_key |
vault_ref + url | API key with optional endpoint URL |
ssh_key |
vault_ref | SSH private key (multi-line) |
certificate |
vault_ref + expires_at | TLS/SSL certificate (multi-line) |
config_block |
vault_ref | .env files, server configs, connection strings (multi-line) |
secure_note |
vault_ref | Free-form encrypted text |
totp |
vault_ref | TOTP seed: agent can compute current 6-digit code |
2.2.2 Secret share¶
Granular per-user sharing with single-use and expiry options.
| Field | Type | Description |
|---|---|---|
| id | UUID | PK |
| secret_id | UUID | FK → secret (CASCADE) |
| user_id | UUID | FK → user_profile (recipient) |
| shared_by | UUID | FK → user_profile (creator) |
| is_single_use | BOOLEAN | If true, share is invalidated after first copy |
| expires_at | TIMESTAMPTZ | Nullable: no expiry if NULL |
| used_at | TIMESTAMPTZ | Set on first copy if single_use |
| status | TEXT | active, used, expired, revoked |
| created_at | TIMESTAMPTZ |
Constraints:
- UNIQUE(secret_id, user_id): one active share per user per secret
- Only the secret's creator can create shares
- Shared users cannot re-share
2.2.3 Secret access log¶
Dedicated audit trail for every vault value read. Separate from the general event table for security isolation.
| Field | Type | Description |
|---|---|---|
| id | UUID | PK |
| secret_id | UUID | FK → secret |
| user_id | UUID | FK → user_profile (who accessed) |
| agent_id | UUID | FK → agent (nullable: set if accessed by agent) |
| access_type | TEXT | reveal (creator views), copy (shared user copies), agent_use (agent reads for operation) |
| ip_address | TEXT | Client IP |
| user_agent | TEXT | Client user agent string |
| created_at | TIMESTAMPTZ |
Retention: Access logs retained for 12 months minimum. Not subject to standard data retention policies: security audit requirements take precedence.
2.3 API endpoints¶
2.3.1 Secret CRUD¶
Create a secret. The request body includes the plaintext value, which the server stores in Supabase Vault and records the vault_ref. The value is never stored in thesecret table.
Request:
{
"name": "Staging Database",
"secret_type": "password",
"scope": "user",
"scope_id": "<user_id>",
"username": "admin",
"url": "https://db.staging.example.com",
"value": "the-actual-password",
"visibility": "private",
"expires_at": null,
"metadata": { "notes": "Rotated monthly" }
}
Response 201:
The value field is accepted on create/update only. It is NEVER returned in any GET response.
value is provided, the old Vault entry is replaced with a new one.
Delete the secret. Removes the Vault entry, cascades to shares and access logs.
2.3.2 Value access¶
Creator only. Returns the decrypted value. Logged insecret_access_log with access_type: reveal.
Response:
Response headers: Cache-Control: no-store, no-cache, must-revalidate
Frontend renders with a mask/reveal toggle.
Creator or valid share holder. Returns the decrypted value for clipboard copy. The frontend copies programmatically and clears the clipboard after 30 seconds. The value is NEVER displayed on screen for shared users.Server checks:
1. Is the user the creator? → allow
2. Does the user have an active share? → check:
- status = 'active'
- expires_at IS NULL OR expires_at > NOW()
- If is_single_use: used_at IS NULL
3. If valid: read from Vault, return value, log access
4. If is_single_use: set used_at = NOW(), status = 'used'
Response: same as reveal. Headers: Cache-Control: no-store
2.3.3 Sharing¶
Creator only. Share with a specific user.Request:
Creator only. List all shares for this secret with status and usage info. Creator only. Revoke a share. Setsstatus = 'revoked'.
2.3.4 Access log¶
Creator or account admin. Returns chronological access history.Response:
[
{
"user_id": "uuid",
"agent_id": null,
"access_type": "copy",
"ip_address": "203.0.113.42",
"created_at": "2026-03-21T14:30:00Z"
}
]
2.3.5 Password generation¶
Generate a secure password without storing it.Request:
{
"length": 32,
"include_uppercase": true,
"include_lowercase": true,
"include_numbers": true,
"include_symbols": true,
"exclude_ambiguous": true
}
Response:
The generated password is returned but NOT stored. The client can then call POST /v1/secrets to save it.
2.4 Agent integration¶
2.4.1 Agent tools¶
| Tool | Trust Level | Description |
|---|---|---|
native_secret_create |
low_risk_write | Create a new secret |
native_secret_list |
read | List secrets by name/type (metadata only, never values) |
native_secret_read |
sensitive_read | Read a secret value (requires per-secret user approval) |
native_secret_update |
high_risk_write | Update a secret's value or metadata |
native_secret_share |
low_risk_write | Share a secret with another user |
native_secret_generate |
read | Generate a secure password |
2.4.2 Approval flow¶
When an agent calls native_secret_read:
- Harness checks: does the agent have the tool assigned?
- Harness checks: is the secret within the agent's assignment scope?
- First access to this specific secret in this session: the agent sends an approval request to the user:
- If approved: value read from Vault, passed to agent's tool execution context
- If denied: agent receives "access denied" and must proceed without the credential
- Subsequent accesses to the SAME secret in the SAME session: no re-approval needed
- Access logged in
secret_access_logwithaccess_type: agent_useand the agent_id
2.4.3 Value handling in agent context¶
The value MUST NOT appear in:
- Agent response text (use secure_fields content type instead)
- Step output_data or input_data (store "vault_ref accessed" not the value)
- Knowledge facts (extraction pipeline skips vault-flagged interactions)
- Event payloads
- Logs
Post-processing filter: After every agent response that follows a native_secret_read call, a filter checks the response text against the recently-read vault values. If a match is found, it is redacted and replaced with [REDACTED: credential]. This is a safety net: the system prompt instructs agents not to display credentials, but LLMs can't be fully trusted.
2.4.4 Secure fields content type¶
When an agent retrieves credentials for the user, the response uses a special content type:
{
"text": "Here are the credentials for Staging DB.",
"secure_fields": [
{
"label": "Username",
"value": "admin",
"type": "text"
},
{
"label": "Password",
"vault_ref": "vault_ref_456",
"type": "masked"
}
]
}
Channel rendering:
| Channel | Secure fields rendering |
|---|---|
| Web app | Card with masked values, reveal toggle (creator), copy button, 30s clipboard clear |
| Telegram | Text only: "I've retrieved the credentials. Open the web app to view them securely." |
| Text only: same message | |
| API | Full JSON including vault_ref: consumer handles security |
| Voice | Text only: "I have the credentials ready. Check the web app." |
The vault_ref is resolved client-side: the web app calls /v1/secrets/{id}/reveal or /v1/secrets/{id}/copy when the user clicks reveal/copy. The actual value is NEVER in the chat message payload.
2.5 Vault security model¶
2.5.1 Value lifecycle¶
CREATE: Client → [TLS] → Server → vault.create_secret(value) → vault_ref stored in secret table
↓
Value encrypted at rest in Supabase Vault
REVEAL: Client → [TLS] → Server → vault.decrypted_secrets WHERE name = vault_ref → value
(creator only) ↓
Logged in secret_access_log, returned over TLS
COPY: Client → [TLS] → Server → vault.decrypted_secrets WHERE name = vault_ref → value
(creator or share) ↓
Share validated, logged, returned over TLS
Frontend copies to clipboard, clears after 30 seconds
AGENT: Harness → approval → vault.decrypted_secrets WHERE name = vault_ref → value
↓
Used in tool execution, NEVER stored in output
Logged in secret_access_log with agent_id
2.5.2 Access control matrix¶
| Action | Creator | Shared User (active) | Shared User (expired/used) | Team Member | Account Admin | Agent |
|---|---|---|---|---|---|---|
| See metadata | ✓ | ✓ (name only) | ✗ | Scope-dependent | ✓ (metadata only) | Scope-dependent |
| Reveal value | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| Copy value | ✓ | ✓ | ✗ | ✗ | ✗ | ✗ |
| Create share | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
| Re-share | ✗ | ✗ | ✗ | ✗ | ✗ | ✗ |
| Revoke share | ✓ | ✗ | ✗ | ✗ | ✓ | ✗ |
| Use value | ✓ | ✗ | ✗ | ✗ | ✗ | With approval |
| View access log | ✓ | ✗ | ✗ | ✗ | ✓ | ✗ |
| Delete secret | ✓ | ✗ | ✗ | ✗ | ✓ | ✗ |
2.5.3 Rate limiting¶
| Endpoint | Limit | Per |
|---|---|---|
/v1/secrets/{id}/reveal |
10/minute | User |
/v1/secrets/{id}/copy |
10/minute | User |
Agent native_secret_read |
5/interaction | Agent |
| Failed access attempts | After 5 failures, 15-minute lockout | User + secret |
2.5.4 Threat mitigations¶
| Threat | Mitigation |
|---|---|
| LLM leakage (agent includes value in response) | Post-processing redaction filter + system prompt instructions + knowledge extraction skip |
| Clipboard exposure | Auto-clear after 30 seconds (frontend). Never displayed on screen for shared users |
| Prompt injection (attacker tricks agent into revealing secrets) | Per-secret approval, scope validation, rate limiting, audit trail |
| Server-side access (insider with DB access) | Values encrypted in Vault. DB access shows vault_ref only. Vault decryption requires separate encryption key access |
| Session hijacking | Same as any JWT-authenticated system. Short JWT expiry. Re-authentication for sensitive operations possible via Supabase Auth |
| Share forwarding (recipient shares value externally) | Cannot prevent. Audit trail records who accessed when. Single-use shares reduce exposure window |
| Stale shares (value already copied before expiry) | Cannot prevent. Rotation reminders encourage credential changes after shares expire |
| Man-in-the-middle | TLS. Cache-Control: no-store. Short-lived responses |
2.5.5 Explicit trade-offs¶
-
Not zero-knowledge. The server handles plaintext values during create/reveal/copy operations (protected by TLS). Supabase Vault encrypts at rest but is not client-side encrypted. A Supabase administrator with encryption key access could theoretically decrypt values. For most users, this is acceptable: it's the same security model as 1Password's web vault, LastPass, and similar services. True zero-knowledge (client-side encryption) is a Phase 2 feature for enterprise customers requiring HSM or BYOK encryption.
-
Not a password manager replacement. No browser extension, no auto-fill, no password health scoring, no import from other managers. The value proposition is agent integration, team sharing within the work context, and elimination of context switching: not competing with dedicated password managers.
-
Agent access is a calculated risk. Allowing agents to read secrets means the LLM has the plaintext in its context window. The post-processing filter and audit trail mitigate but cannot fully eliminate leakage risk. Users must explicitly approve agent access per-secret and should use agent-accessible secrets only for credentials the agent genuinely needs.
2.6 UI and UX¶
2.6.1 Vault page¶
Accessible from the sidebar or as a view on the PA agent. Shows: - List of secrets, grouped by type or filtered by tag - Search by name - Each row: name, type icon, username (if applicable), URL (if applicable), expiry warning, share count - Actions: Copy, Reveal (creator only), Share, Edit, Delete
2.6.2 Create and edit form¶
Adaptive based on secret_type:
- Password: name, username, password (masked input with generate button), URL
- API Key: name, key (masked input), endpoint URL
- SSH Key / Certificate / Config Block: name, large textarea (monospace), expiry date for certificates
- Secure Note: name, textarea
- TOTP: name, seed input, shows current 6-digit code live
All forms include: scope selector, visibility, expiry date (optional), metadata/notes field.
2.6.3 Share dialog¶
- Recipient picker (searches account users)
- Single-use toggle
- Expiry date/time picker (or "no expiry")
- Confirm button
- List of current shares with status and revoke action
2.6.4 Shared secret view (recipient)¶
The recipient sees: - Secret name, type, who shared it, expiry countdown - "Copy to Clipboard" button (large, prominent) - NO reveal toggle, NO value display - After single-use copy: "This share has been used" with no further copy option
2.6.5 Access log view¶
Chronological table: date/time, who accessed, access type (reveal/copy/agent), IP address. Available to creator and account admins.
2.7 Expiry and rotation alerts¶
The existing reminder worker checks secret.expires_at and creates notifications:
| Condition | Notification |
|---|---|
| Expires in 30 days | Info notification (in-app) |
| Expires in 7 days | Warning notification (in-app + push) |
| Expires in 24 hours | Urgent notification (in-app + push + email) |
| Expired | Alert notification (in-app + push) |
Share expiry is handled by the comms worker: when secret_share.expires_at passes, status is set to expired.
2.8 Implementation notes¶
2.8.1 Vault operations¶
-- Create a secret value in Vault
SELECT vault.create_secret('the-actual-password', 'secret_<uuid>');
-- Read a secret value from Vault
SELECT decrypted_secret FROM vault.decrypted_secrets WHERE name = 'secret_<uuid>';
-- Update a secret value
SELECT vault.update_secret('secret_<uuid>', 'new-password-value');
-- Delete a secret from Vault
DELETE FROM vault.secrets WHERE name = 'secret_<uuid>';
The vault_ref stored in the secret table is always 'secret_' + secret.id for consistency.
2.8.2 TOTP code generation¶
For secrets with secret_type = 'totp', the server can compute the current TOTP code:
- Read the seed from Vault
- Generate the 6-digit code using HMAC-SHA1 with the current 30-second time window
- Return the code (valid for ~30 seconds)
This allows the agent to provide 2FA codes: "The current verification code for your AWS account is 847293. It expires in 18 seconds."
2.8.3 Search and discovery¶
Secrets are searchable by name and metadata via the list endpoint. The q parameter searches name and metadata (ILIKE). Agents can use native_secret_list to find relevant secrets: "Do I have credentials for Hetzner?" → searches name.
2.8.4 Tag integration¶
Secrets participate in the existing tag system via entity_tag with entity_type = 'secret'. Tags like "production", "staging", "personal", "shared" help organize the vault.
2.9 Impact on other systems¶
| System | Impact |
|---|---|
| Entity tag system | Add secret to entity_type enum on entity_tag |
| Reminder worker | Add secret.expires_at checks alongside task due dates |
| Knowledge extraction | Skip extraction for interactions that accessed vault data |
| Agent response filter | Add post-processing redaction for vault values |
| Agent manifest | Add native_secret_* tools to the tool registry |
| Secure fields content type | New content type for channel rendering |
| RLS policies | New policies for secret, secret_share, secret_access_log |
2.10 Future considerations¶
- Client-side encryption (Phase 2): For enterprise customers requiring true zero-knowledge. User's master password derives an encryption key. Values encrypted before leaving the browser. Server stores encrypted blobs. Sharing uses recipient's public key for re-encryption.
- Import/export: CSV import from 1Password, LastPass, Bitwarden. Encrypted export with master password.
- Password health: Strength scoring, reuse detection, breach database checking (via HaveIBeenPwned API).
- Hardware key support: WebAuthn/FIDO2 for re-authentication before reveal/copy.
- Secret versioning: Keep history of previous values for rotation auditing.
3. MCP credential injection¶
MCP servers are stateless by design: they receive credentials as HTTP headers on every request and never store credentials or manage token lifecycle. Thinklio handles storage, refresh cycles, and per-request injection. This section covers how credentials flow from the vault into MCP tool calls, including OAuth refresh handling and the credential configuration schema that every MCP server declares in its /meta endpoint.
3.1 Credential injection¶
MCP servers are stateless: they receive credentials as HTTP headers on every request. They never store credentials and never manage token lifecycle.
Request flow:
User sends message → Agent decides to call tool
→ Thinklio resolves credentials:
1. Look up MCP server's credentialConfig
2. Determine scope (platform / account / user)
3. If user-scoped: fetch requesting user's credential from vault
4. If account-scoped: fetch account credential from vault
5. If token needs refresh: refresh it (see 2.3)
→ Thinklio forwards tool call to MCP server with credential headers
→ MCP server authenticates to upstream API using the injected headers
→ Result returned to agent
Header convention per integration:
| Integration | Headers | Scope |
|---|---|---|
| Cliniko | X-Cliniko-Api-Key |
User (each clinician's key) |
| Notion | X-Notion-Api-Key |
Account (workspace integration token) |
| Xero | X-Xero-Access-Token + X-Xero-Tenant-Id |
Account (OAuth, managed by Thinklio) |
3.2 Managed credentials (OAuth)¶
Some integrations (e.g. Xero) use OAuth 2.0 with expiring access tokens. The MCP server does not handle token refresh: Thinklio does.
Xero example:
Admin authorises Xero via OAuth flow in Thinklio admin UI
→ Thinklio receives access_token + refresh_token
→ Stored encrypted in account secrets vault
→ access_token expires after 30 minutes
When agent calls a Xero tool:
→ Thinklio checks if access_token is expired
→ If expired: POST to Xero's /connect/token with refresh_token
→ Store new access_token + refresh_token
→ Inject fresh access_token as X-Xero-Access-Token header
→ Forward tool call to MCP server
The MCP server sees a valid bearer token every time. It has no awareness of the refresh cycle.
For Custom Connections (client_credentials):
Some Xero setups use client_credentials grant (no user interaction, single org). In this case: - Admin provides client_id + client_secret - Thinklio requests a new access_token every 30 minutes - No refresh token needed: just re-request with credentials
3.3 Credential states¶
From the user/agent perspective, a tool's credential state determines what happens:
| State | Cause | Agent behaviour | User sees |
|---|---|---|---|
| Ready | Credentials present and valid | Tool works normally | Nothing: invisible |
| Expired (auto-refresh) | OAuth token expired | Thinklio refreshes transparently, tool works | Nothing: invisible |
| Expired (refresh failed) | Refresh token revoked or invalid | Tool returns error | "The Xero connection needs to be re-authorised. Ask an admin." |
| Missing (account-scoped) | Admin hasn't configured the integration | Tool returns error | "The [integration] hasn't been set up yet. An admin needs to configure it in Settings → Integrations." |
| Missing (user-scoped) | User hasn't added their key | Tool returns error | "Connect your [service] account in Settings → Integrations to use this." |
These messages come from Thinklio's credential resolution layer, not the MCP server. The MCP server simply rejects with "missing header X" if credentials aren't present: Thinklio intercepts this before it reaches the agent and provides the user-friendly message.
3.4 Credential configuration data model¶
Each MCP server registration includes a credentialConfig that describes what it needs:
{
mcpServerUrl: "https://cliniko.api.thinklio.ai/mcp",
credentialConfig: {
scope: "user", // platform | account | user
headers: [
{
name: "X-Cliniko-Api-Key",
label: "Cliniko API Key",
description: "Your personal Cliniko API key. Find it in My Info → API Keys.",
required: true,
}
],
oauth: null, // or OAuth config for managed flows
}
}
For OAuth integrations:
{
mcpServerUrl: "https://xero.api.thinklio.ai/mcp",
credentialConfig: {
scope: "account",
headers: [
{ name: "X-Xero-Access-Token", managed: true }, // injected by Thinklio
{ name: "X-Xero-Tenant-Id", managed: true },
],
oauth: {
provider: "xero",
authorizeUrl: "https://login.xero.com/identity/connect/authorize",
tokenUrl: "https://identity.xero.com/connect/token",
scopes: ["openid", "profile", "email", "accounting.transactions", "accounting.contacts", "accounting.reports.read"],
tokenExpirySeconds: 1800,
refreshable: true,
}
}
}
Part D: MCP tool permissions¶
Part D defines how Thinklio decides, for each channel and each tool call, which MCP tools an agent may actually use. It covers the core intersection principle, the grant model, the resolution algorithm, channel-level downgrade, agent visibility states, delegation chains, whose credentials are used, the /meta endpoint MCP servers expose to advertise their capabilities, and the end-to-end lifecycle for adding and configuring integrations.
1. Core principle¶
In any channel, an agent's effective tool set is the intersection of all human participants' tool permissions.
This prevents privilege escalation via shared channels. A user cannot gain access to data by being in a channel with someone who has higher permissions: the agent's capabilities are constrained to what the least-privileged participant is allowed to see.
2. Permission grants¶
Tool access is granted at three levels, with most-specific winning:
| Level | Scope | Example |
|---|---|---|
| Organisation | All users in the account | "Everyone can use the Calendar Agent" |
| Team | Members of a specific team | "Finance team can use Xero tools" |
| User | Individual user | "Dr. Smith can access Cliniko" |
Grants are stored in the access_grants table:
{
subjectType: "tool" | "agent",
subjectId: Id<"tools"> | Id<"agents">,
scope: "organisation" | "team" | "user",
scopeId: Id<"teams"> | Id<"users"> | null, // null for org-wide
permissionLevel: "deny" | "read" | "standard" | "elevated" | "admin",
accountId: Id<"accounts">,
}
Permission levels align with tool trust levels (see Part B section 4.5):
| Level | What it permits |
|---|---|
deny |
No access at all |
read |
Read-only tools (list, get, search) |
standard |
Read + modify existing data (update status, edit notes) |
elevated |
Read + modify + create/delete (create invoices, book appointments) |
admin |
Full access including destructive operations |
3. Resolving a user's effective tool set¶
For a given user, their effective permissions for a tool are resolved by layering:
1. Start with organisation-level grant (if any)
2. If user is in a team with a team-level grant, apply it:
- If team grant is more restrictive, use team grant
- If team grant is less restrictive than org, org wins (most restrictive)
- If user is in multiple teams, use the LEAST restrictive team grant
(teams add permissions within the org ceiling)
3. If user has a user-level grant, apply it:
- Same most-restrictive-wins rule against the effective level so far
effectiveLevel = min(orgLevel, max(teamLevels...), userLevel)
Important nuance: Multiple team memberships are OR'd (user gets the best of their teams), but the result is still capped by the org-level grant. User-level grants can further restrict but not exceed the team/org ceiling. A user-level deny always wins.
4. Channel tool resolution¶
When an agent receives a message in a channel, the system computes the available tools:
channelParticipants = human participants in the channel (excludes bots/agents)
For each tool in the agent's assigned tool set:
For each participant:
resolve their effective permission level for this tool
channelLevel = min(all participants' effective levels)
If channelLevel == "deny" or tool's trustLevelRequired > channelLevel:
tool is EXCLUDED (invisible to agent)
Else:
tool is INCLUDED with channelLevel as the effective permission
4.1 Permission level downgrade in channels¶
When a channel contains users with different permission levels for the same tool, the tool operates at the lowest common level.
Example: Xero tools in a group chat
The Xero MCP server has tools at different trust levels:
| Tool | Trust level required |
|---|---|
xero_list_invoices |
read |
xero_get_report |
read |
xero_create_invoice |
elevated |
xero_create_payment |
elevated |
xero_update_invoice |
standard |
Scenario: Group chat with Alice (elevated Xero access) and Bob (read Xero access).
Channel effective level for Xero = min(elevated, read) = read
Available tools:
xero_list_invoices → requires read → ✓ available
xero_get_report → requires read → ✓ available
xero_update_invoice → requires standard → ✗ hidden (read < standard)
xero_create_invoice → requires elevated → ✗ hidden (read < elevated)
xero_create_payment → requires elevated → ✗ hidden (read < elevated)
Alice can see invoices and reports in this group chat, but cannot create invoices or payments. If she DMs the agent directly, she gets full elevated access.
Scenario: Same group but with Carol who has no Xero access at all.
The agent cannot use any Xero tools in this channel.
5. Agent visibility states¶
Based on the resolved permissions, agents show different states in a channel:
| State | Condition | UI treatment |
|---|---|---|
| Active | Agent has at least one usable tool in this channel | Normal: agent responds to messages |
| Limited | Agent has some tools available but others hidden due to permissions | Normal, but may say "I can't do that in this chat" if asked for a restricted action |
| Unavailable | Agent has no usable tools in this channel (all denied by permission intersection) | Greyed out / muted indicator. Agent can explain: "I don't have the right access in this group. Try messaging me directly." |
| Needs setup | Agent's tools require credentials that haven't been configured | Shows setup prompt (see Part C section 3.3) |
An agent is never completely invisible in a channel it's been added to: it's either active, limited, unavailable (with explanation), or needs setup. The user always understands why.
6. Delegation chains¶
When a compound agent (e.g. PA Agent) delegates to a sub-agent (e.g. Finance Agent), the permission check applies at every level:
PA Agent → delegates to → Finance Agent → calls → xero_get_report
Permission checks:
1. Is Finance Agent in PA Agent's delegation set? ✓
2. Is Finance Agent granted to all channel participants? ✓ (resolved per section 4)
3. Is xero_get_report in Finance Agent's tool set? ✓
4. Is xero_get_report available at the channel's effective level? ✓ (read ≤ read)
→ Allowed
Principle from Part A: "Delegation does not escalate. Agent-to-agent delegation can only narrow permissions, never widen them."
The delegated agent operates under the intersection of:
- Its own permissions
- The delegating agent's permissions
- The channel's effective permissions (from participant intersection)
No delegation chain can result in a tool call that any channel participant wouldn't be permitted to trigger directly.
7. Whose credentials are used¶
Tool calls use the credentials of the user who triggered the request.
When Dr. Smith asks the PA Agent to "show me treatment notes for Lorraine Salt":
- The PA Agent delegates to the Cliniko tool
- Thinklio injects Dr. Smith's Cliniko API key
- Cliniko returns clinician-level data (treatment notes visible)
When Jane (admin) asks the same question in the same group chat:
- Thinklio injects Jane's Cliniko API key
- Cliniko returns admin-level data (treatment notes may not be visible)
Both are in the same channel, both can trigger the same tool, but the external system's response differs because different credentials are used. This is correct: the external system's own permission model is respected.
This means: In a group chat, if Dr. Smith asks for treatment notes and they appear in the chat, Jane can read them (the clinician chose to surface that information in a shared context). But Jane cannot independently pull the same data: her API key won't return it.
This matches real-world behaviour: a clinician can share patient information with their assistant verbally, but the assistant can't access the clinical system themselves.
For account-scoped credentials (e.g. Xero), the same token is used regardless of which user triggers the request. Access control is handled by Thinklio's permission layer (sections 4 and 4.1), not by the external system.
8. MCP server metadata endpoint¶
Each MCP server exposes a /meta endpoint that Thinklio uses for self-service integration setup.
8.1 Endpoint¶
8.2 Response¶
{
"name": "cliniko",
"version": "1.0.0",
"description": "Cliniko practice management system integration. Provides access to patients, appointments, treatment notes, and invoices.",
"documentationUrl": "https://docs.thinklio.ai/integrations/cliniko",
"credentialConfig": {
"scope": "user",
"headers": [
{
"name": "X-Cliniko-Api-Key",
"label": "Cliniko API Key",
"description": "Your personal Cliniko API key. Find it in Cliniko → My Info → Manage API Keys.",
"required": true
}
]
},
"tools": [
{
"name": "cliniko_search_patients",
"trustLevel": "read",
"description": "Search for patients by last name."
},
{
"name": "cliniko_get_patient",
"trustLevel": "read",
"description": "Get full details of a specific patient."
},
{
"name": "cliniko_get_treatment_notes",
"trustLevel": "read",
"description": "Get treatment notes for a patient."
}
]
}
8.3 Usage¶
Thinklio calls /meta when:
- An admin registers a new MCP server: populates the integration setup UI
- Periodically (alongside tool discovery): detects version changes, new tools
- When a user needs to configure credentials: shows setup instructions
The /meta response is cached and refreshed on the same cycle as MCP tool discovery (every 24 hours or on manual refresh).
8.4 Versioning¶
The version field follows semver. Thinklio can display version info in the admin UI and optionally alert admins when a new version is detected (tools added/removed/changed).
The MCP server's initialize response already includes serverInfo.version. The /meta endpoint provides additional context that MCP's protocol doesn't cover (credential requirements, trust levels, documentation).
9. Integration lifecycle¶
9.1 Admin adds an integration¶
1. Admin → Settings → Integrations → Add MCP Server
2. Enters MCP server URL (e.g. https://cliniko.api.thinklio.ai/mcp)
3. Thinklio calls /meta on the MCP server
4. UI shows: name, description, credential requirements, tool list
5. If account-scoped: admin provides credentials (or starts OAuth flow)
6. If user-scoped: admin enables the integration; users configure their own keys later
7. Thinklio calls MCP initialize + tools/list to discover and register tools
8. Tools appear in the Tool Library
9.2 Admin assigns tools to agents¶
1. Admin → Agent Studio → select agent
2. Add tools from Tool Library (individually or by integration group)
3. Optionally set trust level requirements per tool per agent
4. Save: agent_tools records created
9.3 Admin assigns agents and tools to teams¶
1. Admin → Teams → select team → Permissions
2. Grant access to agents and/or individual tools
3. Set permission level (read / standard / elevated)
4. Save: access_grants records created
9.4 User configures personal credentials¶
1. User tries to use an agent that needs user-scoped credentials
2. Agent responds: "Connect your Cliniko account in Settings → Integrations"
3. User → Settings → Integrations → Cliniko → enters API key
4. Key stored in user's secrets vault
5. Next tool call succeeds: credential resolved from vault
10. Summary¶
| Concern | Where it lives | MCP server's role |
|---|---|---|
| Credential storage | Thinklio secrets vault | None: receives credentials per-request |
| Token refresh (OAuth) | Thinklio credential manager | None: always receives valid token |
| Tool permission grants | Thinklio access_grants table | None: Thinklio decides which tools to expose |
| Channel permission resolution | Thinklio governance layer | None: if the call reaches the MCP server, it's permitted |
| External data-level access | Upstream API (e.g. Cliniko) | Passes through the injected credential |
| Tool discovery | MCP protocol (tools/list) | Returns available tools with schemas |
| Integration metadata | /meta endpoint |
Returns credential config, trust levels, docs |
| Trust level enforcement | Thinklio governance layer | MCP server declares trust levels in /meta |
References¶
- Convex access control patterns (RLS, row-level security): see
11-convex-reference.mdsection 8 (RLS / row-level security) and section 9 (triggers). - Clerk authentication and organisations: see
02-system-architecture.md(identity & auth) and12-developer-guide.md(Convex + Clerk setup). - Agent trust levels and execution tiers: see
03-agent-architecture.md(trust levels, execution tiers, rate limiters). - Tool catalogue and registration: see
09-external-api-and-tool-integration.md(MCP tool registration, server reference). - Data model tables referenced: see
04-data-model.mdforaccount,account_user,team,team_member,agent,agent_assignment,access_grants,secret,secret_share,secret_access_log,mcp_server,mcp_tool,credential_configdefinitions. - Content policies and system prompt injection: see
03-agent-architecture.md(contextHandler, system prompt assembly). - Governance component integration: see
03-agent-architecture.md(component integration) and11-convex-reference.mdPart B for building custom components.
Revision history¶
| Version | Date | Change |
|---|---|---|
| 1.0.0 | 2026-04-16 | Initial consolidated release. Supersedes pre-consolidation docs 08 (Security Model v03), 36 (Secrets Vault v01), 47 (Governance Policy Framework v02), 52 (MCP Credential & Permission Model v01). Editorially updated to Convex + Clerk architecture: Supabase Auth replaced with Clerk throughout; Supabase Vault storage note added to Part C (envelope encryption on Convex tables preserves API surface); cross-references retargeted to the 14-document canonical set. No content loss beyond renumbering and sentence-case normalisation. |
| 1.1.0 | 2026-11-04 | § 4.2 the four roles (owner, admin, member, read only; DEC-60) and the organisation, teams and individuals (DEC-61); knowledge scoped by place (DEC-63); § 3.3 and § 4.2 for Thinklio's own accounts and members (RM-7, DEC-57). This row added by the scope audit (DS-11), from the commits of 3 and 4 November 2026. The rest of the doc is still April's (tech debt R7) |
| 1.2.0 | 2026-11-08 | Part B rewritten to the policy engine as built (RM-36): the rules, the decision, approvals, spending limits, operating hours and content rules, and where they're managed. April's framework (categories, templates, the resolver) is in this doc's history up to 1.1.0 |
| 1.3.0 | 2026-11-08 | § 4.2: who can open a space follows its owner, and the default role (RM-37, DEC-84, DEC-139); team templates (DEC-140); Part B § 7: a team's rules on its card |