# Tek Local Gateway: TekPartner V3 integration brief

## TP-203 — Delete uploaded files (released)

API **7ef7cfd**, MCP/worker **a3e0a79** and the Documents web action are verified
live (PR #91, October 2 Mountain / October 3 UTC). Skill **1.0.25** includes this
confirmed handoff. This is additive; no new credential or permission is required.
No Homebase/Gateway client update has been confirmed. The owner relays this handoff.

- Refresh `tools/list`, the local `tekpartner_document` action allowlist and cached
  document capabilities now; reconnect if the client
  caches schemas. Accept the additive `delete` capability (default false on old APIs).
  The document tool now advertises `destructiveHint: true`; preserve a deliberate
  user-authorized confirmation for its delete action.
- Add `action: "delete"`, `documentId`, and top-level `expectedVersion`. No new tool
  name, credential, permission or project scope is needed. API/SDK use
  `POST /v3/documents/:id/delete` / `deleteDocument(id,{expectedVersion})`.
- Gate deletion on explicit user intent, current write permissions and own-upload
  ownership. Archive remains the reversible option. Agents cannot delete somebody
  else's upload; human library admins have broader record administration.
- Display CONFLICT as “still linked”; do not remove relationships automatically.
  STALE_WRITE requires re-reading and reconfirming. Retry an unknown outcome with
  the same ID/version/credential. `cleanupPending` is normal asynchronous cleanup.
  Reads of the removed document return NOT_FOUND and share links stop working.
- Read-only live acceptance: verify whoami, organization, capabilities and schema.
  Destructive acceptance belongs in a disposable environment: own upload deletion,
  stale/other-owner/project-only denial, reference conflict, safe retry, no list or
  download after deletion, revoked shares, audit and retried storage cleanup.
- Relay the confirmed notice to downstream clients. Queued notices are not evidence
  that Homebase or its consumers refreshed.

## TP-201/202 — Homebase session reliability and small icons (released)

Feature API/web **84c9dca** is verified live (PRs #88/#89, October 2 Mountain /
October 3 UTC, 2026). MCP **faf611c** and worker **43cfea0** remain unchanged.
Skill **1.0.23** records the confirmed release; 1.0.22 introduced the guidance.
The public manifest identifies the published package. No new MCP tools, required
arguments or permissions are introduced. Existing document-list defaults remain.
Signed-in checks verified full-range session totals, icons, editable agent details
and default document-library filtering; anonymous range reads are denied.
Please relay the lifecycle guidance to downstream clients and report each
acknowledgement separately; neither delivery nor client adoption is assumed.

### Copyable instructions for the Tek Homebase agent

Implement reliable TekPartner session reporting in your existing Gateway adapter.
Keep the current identity and capability validation; do not broaden permissions.
Use `agent-sessions.read` and `agent-sessions.write` only where already granted.

1. Identify each local run with its own durable pointer to the remote report,
   principal, organization and project. Resume a matching run with `get`/`resume`;
   do not reuse a single global session or create a report for every prompt.
2. Checkpoint actual milestones using `tekpartner_session action=checkpoint`,
   current `expectedVersion`, `client`, a fresh idempotency UUID, concise outcome
   facts and only metric deltas not previously acknowledged. Keep original input
   and key across uncertain retries; receipts last 24 hours. `heartbeat` is for
   live execution, not an idle chat. Do not repeatedly add boilerplate summaries.
3. Put finalization in a durable cleanup/outbox path covering success, failure,
   timeout, cancellation and interruption. Save the closing facts before sending.
   On success: state what changed, what was verified and what remains, then
   `get`/`get_actions` and `update` with the current version and allowed terminal
   status. Completed is for completed work; resumable interruption stays explicit.
   Character/token counts alone are not an outcome report.
4. On restart, reconcile pending finalization against remote state. Reuse exact
   checkpoint/create/span receipt inputs within their lifetime. After any replay,
   reload before another versioned write. On `STALE_WRITE`, reload and reconcile;
   never blindly increment. Stop on denied scope/revocation; retain pending facts
   locally and expose the safe error code/request ID.
5. Repair old reports only when your own runner evidence proves the run ended and
   the outcome. Read current versions, use permitted transitions and preserve
   actual uncertainty. Do not invent reports or close another agent's sessions.
6. For useful tool breakdowns, append bounded, completed `tekpartner_span` records
   with actual `startedAt`/`endedAt`, `name` equal to the tool name, and
   `attributes: {"kind":"tool"}` (or explicit `toolName`). Send a fresh UUID per
   real span, retained on uncertain retry. Never put prompts, arguments, secrets
   or tool output in trace attributes. Metric call totals remain separate from
   traced-call coverage; no fabricated timings or backfilled traces.
7. Pre-size custom icons to a small square (normally 512px, under 256 KiB), upload
   with `tags:["record-icon"]`, then set `tekpartner_agent_icon` using the current
   icon version. Keep logo space via `iconPadding`; do not upload a 5 MB original
   for an avatar. Existing files must not be deleted during this client update.

Refresh the maintained skill/manual and reload local agent instructions after
publication. Keep existing wrappers for `tekpartner_session`, `tekpartner_span`,
`tekpartner_document` and `tekpartner_agent_icon`. Add only missing existing tools
to a restrictive local allowlist if this integration requires them and existing
permissions allow them. No tool-catalog invalidation, mandatory reconnect,
credential rotation or gateway restart is introduced by this slice. If your own
client caches schemas/instructions, refresh that cache without switching identity.

Acceptance: one real run produces one report, useful closing facts and truthful
terminal status; a simulated interrupted delivery replays exactly once; restart
recovers pending finalization; stale versions reconcile; denied scopes remain
denied; tool names and timing reflect actual spans. Verify `whoami`, scoped
capabilities, current report status and pagination read-only first. Report your
installed client version and results. TekPartner has not directly connected to or
verified the Homebase Gateway.

The web's new range aggregation is HTTP/SDK-only: `getAgentSessionActivity` reads
`GET /v3/agent-sessions/activity` with inclusive `from`/`through` UTC dates and
optional agent/project/client/status/search filters. It rechecks existing session
read scope on every request. Do not invent an MCP activity action. Optional
`runtime`/agent-icon response projections may be absent through the existing MCP
build; clients must tolerate their absence and must not alter source timestamps.

Integration handoff, updated 2026-10-02 UTC (October 2 Mountain). Current Homebase target: `HiTek-Agency/Tek-Gateway`, with its adapter in `packages/gateway/src/mcp`. Tek-Agent-Suite is a separate product; its original audit at `ef6b9bf` and paths retained below are historical reference, not Homebase's implementation. Verify the installed client before planning changes. Use the [agent manual](/agent-guides/agent-manual.md) for first-project setup and operating policy. The [public skill installation page](https://www.tekpartner.app/agents) distributes both guides without login; service credentials remain private and separately issued.

## Readable inline references — TP-199 (released)

Authoring guidance update for existing and newly onboarded clients. Fetch skill
**1.0.21** from the current public release and reload the agent instructions.
Use descriptive Markdown links with IDs returned by current scoped tools; examples
are in [the manual](https://www.tekpartner.app/agent-guides/agent-manual.md#readable-links-to-tekpartner-records).
The web renders recognized bare UUIDs and internal record/document URLs with
reader-authorized names. Do not rewrite old records merely to change display.
Code, external links and repository paths remain literal; missing or inaccessible
records disclose no new title. No AI call, mention or relationship is created.

No MCP tool, argument, permission, Gateway allowlist, capability contract or
connection change is required. The web uses a human-only exact-reference HTTP
reader; do not expose it through an independent agent wrapper or borrow a human
identity. Existing create/update retry and version rules stay unchanged. MCP
remains `faf611c`; API/web feature release is `fc85dcb` (PR #84), verified
October 2 with signed-in named-link navigation and denied anonymous lookup.
Skill 1.0.21 records that receipt; 1.0.20 introduced the authoring guidance.
No Homebase instruction reload is claimed until acknowledged.

Acceptance: write a descriptive link using a known authorized task/document ID
as part of real work; confirm the web shows a readable link, follows the right
record and keeps a meaningful custom label. Use disposable data for denied-scope,
missing-ID and retry testing. Merely pasting a repository filename must not invent
a stored document. Relay this guidance to downstream agents when authorized;
record delivery and acknowledgement separately.

## Browser-approved onboarding follow-up — TP-169 (released)

Add an optional **Connect to TekPartner** flow using the public HTTP bootstrap in
[the connection guide](https://www.tekpartner.app/agent-guides/agent-onboarding.md).
It opens `https://www.tekpartner.app/connect?code=…` for the person. Supply suggested
name, purpose, client label, capability allowlist, project names/IDs, expiry and
review interval as defaults. The person can change every restriction. The chosen
organization and final edited policy are authoritative; never silently widen an
unmatched project. Existing connections and existing MCP tools remain unchanged.

Use a temporary RSA-2048 key pair and independent 32-byte request token. Keep the
private key/token and exact UUID create input in the local vault before dispatch;
never send them through a language model, log or chat. Poll at five-second intervals
and honor Retry-After. Decrypt the returned RSA-OAEP-SHA256 envelope locally, verify
whoami's exact agent/organization/credential IDs, then store the key in the existing
vault and refresh the connection. Replay only the same request within ten minutes.
Never fabricate success from approval alone: distinguish awaiting approval,
approved/collecting, verified/connected, declined, expired and unknown outcome.

Do not add credential approval MCP tools. Only the real administrative browser
session can review/decide; normal agent keys cannot. Preserve owner/admin control,
current capability validation and policy intersection. Do not attach an existing
agent based on matching name, borrow credentials, broaden access, or retry an
uncertain create with another UUID. A duplicate profile name needs human resolution.

Acceptance: edited narrower restrictions become the issued profile/key; denied or
expired requests issue nothing; wrong private keys cannot decrypt; exact retries
return one encrypted credential; post-approval revocation prevents collection/use;
whoami and capabilities pass and unauthorized project reads remain denied.
No direct Gateway connection or installed Homebase acceptance is claimed. API and feature web are released as `1dd473b` (PR #50); API workflow
36926503665 and Vercel deployment `dpl_FgvsN657yrtfWSXWVrPhzuw8WX2c` succeeded.
MCP remains `faf611c`, worker `7791f1c`; no tool-catalog refresh is required for
existing keys. Fetch skill 1.0.19 for this cumulative handoff. After implementing
optional bootstrap, verify the exact new identity and refresh that connection.
Homebase implementation and downstream acknowledgement remain unconfirmed.
Please relay this setup change to downstream client maintainers and report their
acknowledgements separately.

## Tek Homebase handoff: September 30 product update

**Contact profile follow-up (TP-162):** extend Homebase's existing contact
create/update wrappers with optional `address`, nullable HTTP(S) `website` and
`socialLinks`. Address keys are `line1`, `line2`, `city`, `region`, `postalCode`,
`country`; social entries are `{label,url}` with HTTP(S) URLs, maximum 16.
Keep email/phone and direct `companyId` available. Discover the company record
before linking; do not infer an organization or borrow another identity.
PATCH replaces supplied address/link collections; null clears address/website
and [] clears links. Omission preserves existing data. Keep expectedVersion,
create idempotency, current CRM capabilities and organization-scope requirements.
Refresh tools/list and cached schemas after confirmed API/MCP release; the tool
name/count/permission set is unchanged. Test roundtrip, omitted-field preservation,
clear semantics, stale writes and denied foreign-company access in disposable data.
This is a client handoff only; no direct Gateway connection or installed-client
acceptance is claimed. Confirm released versions against the receipt below.

**Focus follow-up (TP-159):** the web landing is now one Your focus destination
with personal Week/Month defaults, compact month week-range selectors, optional
full calendar, selected-day deadlines and relevant ongoing project work. Premium AI briefs run in a separate web
server client using API-authorized evidence. This feature adds no MCP tool or
capability flag; keep the existing 47-tool catalog and current work permissions.
Do not expose the internal `/v3/focus/brief-client/*` endpoints or server key to
Homebase, and do not create wrappers for managing someone else's personal defaults
or premium access. Existing deterministic project/work/release/pipeline tools
remain the source for an agent's own reasoning. The limited pilot and broader paid
plan provisioning are separate; admin status alone does not grant AI access.

**Focus cards and cost log (TP-163):** compact AI cards use current work/release
sources and expandable detail. Platform Admin is a human user-menu destination
with an explicit grant, independent of organization admin or premium entitlement.
Its own sidebar contains Organizations, Features & Plans, Billing and Costs,
including a site-owned weekly cost email. Draft plans do not charge and Stripe
checkout remains disabled. The call log and internal usage receipts are not agent
tools. No new MCP command,
permission or refresh requirement is introduced by this web/API feature.

**Private notepad (TP-165):** the web notepad keeps private human drafts and offers
reviewed task creation plus separately entitled AI suggestions. Existing
`tekpartner_note` continues to mean shared KnowledgeRecord notes. Do not map it to
private drafts or expose `/v3/notepad/*`, delegated model-client endpoints, server
keys or platform grants through Homebase. There is no new MCP command or required
Gateway wrapper in this slice. Once a person creates a task, agents can work with
that normal task using their existing authorized tools; this does not grant access
to its private source note. Desktop and explicitly shared agent notes remain later
work. TP-165 is released as API/feature web `6b8fd8f` (PR #47, following #46). The two additive
migrations and exact human pilot grants are verified. This handoff does not claim
an installed Homebase change. The reviewed follow-up makes source validation and
AI claims atomic, counts cache retries once, safely handles deleted pending images,
and includes Focus/Notepad cost totals in the weekly email. It introduces no
additional MCP command or refresh requirement.

This is the single cumulative handoff for agent icons, scoped project creation,
collaboration, roadmaps, work pipelines and personal Focus reads. Inspect Homebase's
current connector, wrappers, allowlists, approval policy and caches first; the
Gateway paths below are historical reference points. Use disposable data for tests.

**Confirmed feature releases:** API/feature web `6b8fd8f` (PR #47, following #46), worker
`7791f1c` (PR #44), MCP `faf611c` (PR #41); service version `0.1.0`. Actual owner
acceptance confirms
separate Platform Admin, AWS cost reads and compact Luna Focus cards with usage
receipts and cached reuse. Anonymous platform reads return 401; actual independent
agent reads return 403. No new MCP command or Gateway verification is implied.

Fresh authenticated MCP acceptance on 2026-10-01 at 01:33 UTC verified 47 tools,
identity/current-work capabilities, self-icon/release/work-pipeline reads, contact
address/website/socialLinks and existing contact pagination. The additive Contact
and TP-163 migrations/narrow grants are applied. This cumulative handoff is
packaged in skill `1.0.17`; verify that version in the public manifest before
updating the installed skill. The endpoint remains
`https://api.tekpartner.app/v3/mcp`; keys need no reissue. If you have not yet
incorporated the earlier MCP changes, reconnect and refresh your cached catalog.
TP-163/165 require no additional MCP refresh. Publishing this guide does
not mean Homebase or downstream consumers have refreshed.

**Homebase compatibility correction:** [Tek-Gateway PR #17](https://github.com/HiTek-Agency/Tek-Gateway/pull/17),
source commit `86a4a01a`, repairs capability parsing and safe diagnostics against
Gateway 0.6.98 build 308. It is an unreleased source patch. Both capability shapes
parse and 71 focused tests pass; build and audit pass. Full checks on this Mac
have six unchanged artifact-storage test failures (unsupported filesystem type 25)
and one unchanged update-cleanup failure. Complete those gates on a supported host
before publication, then verify Tek's existing connection read-only. The affected
host and installed version are still unconfirmed. Do not install the source-only
placeholder-key build, copy another agent's credential or treat parser replay as
Tek's acceptance. The exact historical 21:48 UTC response was not captured.

1. Reconnect after confirmed deployment, reload `tools/list`, and refresh approved
   wrappers/allowlists. Verify `tekpartner_whoami` matches the configured principal
   and organization, then read activity and current-work capabilities. Parse full
   results from `structuredContent`; handle `isError` and `error.code` explicitly.
   Capability responses are additive: validate known booleans, required fields and
   transition values while ignoring unsupported extra response fields. Extra fields
   must never create local actions or widen arguments. Homebase through 0.6.98 uses
   strict response objects that reject `workstreams.mutations.members` and the newer
   top-level `releases`/`pipelines`, blocking shared preflight even for identity reads.
   Update that validator before assuming reconnect alone repairs the connection.
   Keep malformed known fields denied and report bounded schema paths/requirements,
   never received values, arbitrary remote keys or credentials. This correction
   needs no credential rotation or permission expansion; verify the installed client
   through its existing bound connection after applying its reviewed fix.
2. Add `tekpartner_agent_icon` with action-aware local handling: `get` is a read;
   `update` is a mutation subject to the existing local approval policy. Omit
   `agentId` to use the authenticated principal. Read `{icon, canUpdate}` first,
   then send `{action: "update", update: {expectedVersion, ...intendedFields}}`.
   Allowed fields are `avatarUrl` (HTTPS), `iconDocumentId`, `iconEmoji`,
   `iconColor` (`#RRGGBB`) and `iconPadding`. Clear unused image/symbol sources
   with null; priority is document, URL, emoji/symbol, initials. Never use the
   general agent profile tool to edit access or credentials.
3. For image uploads, use the existing document tool and save its returned document
   ID, not a temporary thumbnail URL. Document use still needs documents.read and
   organization scope in both policies; upload additionally needs documents.write.
   Project-only agents can use emoji/symbols or HTTPS images without broadening
   file access. On stale or uncertain icon updates, read/reconcile before retrying.
4. Remove any local organization-wide-only rule for project creation. Use live
   `tekpartner_capabilities {surface: "current_work"}` and `creates.project`,
   while preserving local approval gates. The existing create call remains
   `{action: "create", name, idempotencyKey}`. Projects Read/Manage and overlapping
   project scope in both policies permit creation; the API atomically adds only
   the new project to the caller profile and creating key. Do not issue a second
   policy-edit request. Other keys and unrelated projects remain restricted.
5. Keep the same credential, idempotency UUID and exact input after an uncertain
   project create. Replay never restores removed access. Refresh whoami, capability
   and project-list caches after creation; reload profile/key versions before any
   later authorized administration. A full 250-project scope returns CONFLICT and
   leaves no new project/grant. Do not retry with a new key to bypass the limit.
6. Test using mocks or a disposable environment: self-icon read/save/stale recovery,
   denial for another principal, Project A-only creation of Project B and immediate
   work inside B, denial for unrelated Project C and a different key, one project
   on retry, and denial after access removal/revocation. After live release use
   read-only acceptance unless a real requested write is separately authorized.
7. Accept additive workstream `members` and capability `workstreams.mutations.members`.
   Missing flags fail closed. Human-session clients can use `tekpartner_workstream`
   action `set_members` with `workstreamId`, `expectedVersion`, and the complete
   `memberIds` set. Keep this action unavailable to independent agent keys. Project
   and workstream participation is separate from task assignment; do not add
   assignees just to enable contribution. Reload member/version caches after changes.
8. Add `tekpartner_release` with action-aware handling: `list`, `get`, `milestones`
   and `work` are reads; `create`, `update`, `assign_workstream` and `release` are
   mutations under the existing local approval policy. Read live `releases.read`
   and `releases.manage` capability flags. Use stable project/release IDs; version
   labels are display values. Create uses a fresh idempotency UUID and `create`
   object. Update carries `update.expectedVersion`. Workstream placement carries
   its current `expectedVersion`, destination `releaseId` (null unplans), and
   `position`. Refresh both release counts and workstream/version caches afterward.
9. Read release work and milestones with pagination. A released record is an
   immutable snapshot including unfinished work; do not equate release with all
   tasks completed. Live workstreams can move to later plans without rewriting past
   releases. `release` records a historical snapshot and requires explicit intent;
   after uncertain publication, get the release before retrying. Read requires
   project and work read capabilities plus full project scope in both policies;
   management also needs projects.write. Exact item scope is insufficient.
10. Add `tekpartner_work_pipeline` (distinct from CRM `tekpartner_pipeline`). `get`
    is a read; `configure` and `move` are mutations. Check `pipelines.read`,
    `pipelines.configure` and `pipelines.move`. Configuration uses stable UUID stage
    IDs, name, hex color, canonical status, array order, `expectedVersion` (0 on first
    setup), and an idempotency UUID. Send the full intended configuration, preserving
    IDs for renamed/reordered stages. Keep at least one stage for every canonical
    state. Used stages cannot be deleted or reclassified until their work moves.
11. Pipeline move takes `itemId` and `move: {stageId, expectedVersion,
expectedPipelineVersion}`. Reload item and pipeline on stale or uncertain writes.
    Existing status transitions and completion timestamps remain authoritative.
    Optional `pipelineStage` on work items is additive; older status writes clear
    incompatible explicit stages and fall back to the first stage for the new state.
    Released history retains its recorded stage name/color even after later changes.
12. For human personal views, API/SDK list queries accept `participation: "mine"`
    on projects, workstreams, tasks and tickets. This is an additional relevance
    filter, never authorization. It is applied before pagination. Service project/
    workstream participation lists are empty; service work lists match its actual
    assignment. Continue paging and disclose partial loading. Do not infer complete
    priority counts from a capped list. Clear caches on account/organization change.
13. Extend isolated acceptance to roadmap create/retry/edit/group/release, immutable
    history after a live move, forbidden scope/role, stage rename/reorder/move,
    old-client status updates, stale item/pipeline versions and uncertain retries.
    No production mutation probes or invented work are authorized by this guide.
14. Return a concise handoff with changed Homebase files, tests, actual API/MCP/skill
    versions, tool refresh result and remaining gaps. Identify which clients have
    refreshed, which only received a notice and which have not acknowledged. Relay
    confirmed compatibility information to downstream consumers when authorized.

See the [agent manual](/agent-guides/agent-manual.md) for complete examples and
permission boundaries. The linked source correction is not an installed Homebase
release. New feature wrappers and actual connection acceptance remain Homebase
handoff work.

## Outcome and existing foundation

Give each local agent a dedicated TekPartner identity and credential, dated or valid until revoked. Let it read project context, create/update authorized work, leave concise evidence and exchange durable requests. Keep the existing Gateway runtime, approvals and vault; do not create another desktop app or mirror TekPartner’s database.

The original audit identified these integration points; confirm their current paths:

- `packages/agent-schema/src/v1.ts`: `McpServerConfig` with `id`, `transport`, `url`, `credentialRef`, `enabled`; agent configurations carry `mcpServers`.
- `packages/vault`: local secret custody and fail-closed `found | not-found | error` reads.
- `packages/catalog/src/tool-catalog.ts`, `apps/gateway/src/tools/toolkit.ts` and `apps/gateway/src/loop/agent-runner.ts`: declarative tools, factories and the agent loop.
- `apps/gateway/src/approvals/enforcer.ts`: execute-time approval tiers.
- `packages/execution` and `packages/db-gateway`: signed commercial execution, durable approvals, audit/results, replay protection and outcome-unknown recovery.

The original audit predates the Gateway MCP work. Do not recreate an adapter based
on that old snapshot. Check the installed connection and run the acceptance
sequence below; use the deliverables here only to close observed gaps.

## Build sequence and deliverables

1. Add the host MCP client manager with vault lookup, pinned-origin transport,
   cancellation and credential/configuration lifecycle isolation. Deliver a
   connection status view showing identity, organization and errors without secrets.
2. Register curated action wrappers through the existing tool factory and approval
   enforcer. Start with identity, capabilities, project/work reads and contract
   discovery. Normalize each response shape; page lists and handle empty results.
3. Add approved writes with durable input/idempotency receipts and stale-draft
   recovery. Prove retries and actual attribution on disposable data before enabling
   writes for a real connection. Add CRM/files/session controls only when needed.
4. Add the optional inbox trigger after the execution boundary works. Persist
   deduplication and outcome-unknown recovery; do not treat delivery as execution.
5. Install the V3 skill for the calling agents. Ship the supported operation policy,
   test evidence and remaining limits with the integration. Keep this brief and the
   manual canonical rather than generating a second documentation tree.

Other tools can consume the same MCP contract without the Gateway-specific
factories. Reuse their own secret store, execution policy and durable operation
records. The HTTP/SDK path is available for typed interfaces and larger files;
neither transport grants extra permissions. No legacy import or database mirror
is part of client onboarding.

## Connection and local custody

The V3 API and MCP run on AWS; Vercel hosts the web app. Use `https://api.tekpartner.app/v3/mcp`, Streamable HTTP, and a V3 service key with audience `tekpartner-api`. A signed-in owner or administrator issues the key in TekPartner using their current browser session; no separate verification sign-in is required. No OAuth client secret, browser cookie, shared owner identity or J26 compatibility adapter belongs in this connection.

This entry illustrates the audited agent schema; match the current Gateway's
configuration format and keep credential custody in its existing vault:

```json
{
  "mcpServers": [
    {
      "id": "tekpartner_v3",
      "label": "TekPartner",
      "transport": "http",
      "url": "https://api.tekpartner.app/v3/mcp",
      "credentialRef": "mcp:tekpartner-v3:local-agent",
      "enabled": true
    }
  ]
}
```

Store the token only in the host vault at that reference; inject `Authorization: Bearer <token>` at transport dispatch. Do not put headers or secrets in synced agent configuration, model context, tool arguments, audit bodies or the cloud protocol. A vault error must fail closed, not be treated as a missing optional credential. Use separate profile/credential pairs for independently acting agents and separate credentials per connection.

For a lasting Gateway connection, the human owner chooses **Until revoked** when issuing the key. `whoami.credential.expiresAt` is then `null`; treat this as no scheduled expiry, never as an expired date or parse failure. `reviewAt` is advisory. Continue to honor remote revocation/suspension and the bounded overlap when a key is rotated. Do not implement an artificial Gateway expiry for a lasting key.

Pin the approved HTTPS origin/path. Do not forward authorization to redirects or a user-supplied host. Isolate client sessions by credential and configuration revision; disconnect on disable, rotation or revocation. A protocol session ID is connection state, not an authentication credential. Proposed defaults: 30-second connection timeout, 60-second tool timeout, bounded responses and cancellation support.

Native human sign-in remains a separate system-browser/PKCE integration. Do not describe an unimplemented OIDC flow as the current service-key onboarding path.

## Curated calls and permissions

Initialize the MCP client, then `tools/list`. Validate the approved tool names and input shapes; a catalog change must not automatically expand the local allowlist. At every session start call `tekpartner_whoami`, `tekpartner_activity` (`list`, limit 10), and `tekpartner_capabilities` (`surface: current_work`). Bind the returned `principal.id` and organization to the configured connection. Stop on mismatch.

| Gateway intent                       | V3 MCP call                                                                                                                                                                             |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Identity, readiness and diagnostics  | `tekpartner_whoami {}`, `tekpartner_capabilities {surface: "current_work"}`, `tekpartner_health {}`, `tekpartner_version {}`                                                            |
| Discover projects                    | `tekpartner_project {action: "list", limit: 20}`; `get` with `projectId`                                                                                                                |
| Read/edit own agent icon             | `tekpartner_agent_icon`: `get`, then `update` with nested `update.expectedVersion` and intended icon fields (released in TP-150)                                                        |
| Create an approved project           | `tekpartner_project {action: "create", name, idempotencyKey}`                                                                                                                           |
| Discover/create an outcome group     | `tekpartner_workstream`: `list` with `projectId`, `get` with `workstreamId`, or `create` with `projectId`, `title`, `idempotencyKey`                                                    |
| Discover/read/create work            | `tekpartner_task` / `tekpartner_ticket`: `list`, `get` with `workItemId`, `create` with `projectId` and/or `workstreamId`, `title`, `idempotencyKey`                                    |
| Read/create execution steps          | `tekpartner_task`: `list_steps` / `create_step` with parent `workItemId`; create also needs `title`, `idempotencyKey`                                                                   |
| Edit a work item                     | The matching task/ticket tool: `update_details`, `update_status`, `update_priority`, `update_timeline`, `update_work_type`; current `workItemId`, `expectedVersion` and intended fields |
| Read/write progress                  | `tekpartner_comment`: `list`, `create`, `reply` with `entityType` (`task`/`ticket`), `entityId`; writes add `content`, `idempotencyKey`; reply adds `parentId`                          |
| Plan project releases and milestones | `tekpartner_release`: `list`, `get`, `milestones`, `work`, `create`, `update`, `assign_workstream`, `release`; capability and version checks as above                                   |
| Configure and move project work      | `tekpartner_work_pipeline`: `get`, `configure`, `move`; distinct from human-managed CRM pipelines                                                                                       |
| Activity                             | `tekpartner_activity {action: "list", limit: 10}`; optional entity filters per live schema                                                                                              |
| Read knowledge                       | `tekpartner_knowledge`: `list`, `get` with `knowledgeId`; `tekpartner_search {action: "query", query, types: ["knowledge"]}`                                                            |
| Maintain shared knowledge            | `tekpartner_knowledge`: `create` with `kind`, `title`, optional `body`/context, `idempotencyKey`; `update` with `knowledgeId`, `expectedVersion` and intended authored fields           |
| Record/recover agent work            | `tekpartner_session`: `create`, `current`, `list`, `get`, `get_actions`, `checkpoint`, `resume`, `heartbeat`, `update`; `tekpartner_span`: `create`, `list`                             |
| Find a recipient                     | `tekpartner_agent_message`: `list_recipients` with intended `projectId`/`workItemId`, optional literal `search`, `limit` and `cursor`                                                   |
| Read an inbox                        | `tekpartner_agent_message {action: "list", direction: "inbox", limit: 20}`; follow every page                                                                                           |
| Inspect a request                    | `tekpartner_agent_message`: `get` / `get_actions` with `messageId`                                                                                                                      |
| Send/reply                           | `tekpartner_agent_message`: `send` with `senderAgentId`, `recipientAgentId`, `subject`, `body`, `idempotencyKey`; context and decision policy per manual; reply adds parent ID/version  |
| Acknowledge/report outcome           | `tekpartner_agent_message`: `update_status` with `messageId`, `expectedVersion`, allowed `status` and result evidence                                                                   |

Start with `projects.read`, `work-items.read`, optionally `knowledge.read`. Add `projects.write` for project/workstream creation and single-record edits, and `work-items.write` for work creation/edits/comments. Knowledge authoring needs `knowledge.read/write`; allow create/update only within the manual’s context and field boundaries. Sessions need `agent-sessions.read`, plus `agent-sessions.write` for the actual agent’s own reports. Recipient discovery, inbox reads and request inspection (`get`/`get_actions`) need `agent-messages.read`; sends and acknowledgements additionally need `agent-messages.write`. Configure overlapping project scopes in both profile and credential. Project creation with projects.read/write atomically adds only the new project to the creating profile/key, preserving existing restrictions and other keys. Read capabilities again after policy failures; replay never restores revoked access. Exact work-item grants cannot create children. Read current gates rather than copying a permanent “all access” list.

Do not expose unsupported independent-agent actions: assignment, batch writes, profile/credential administration, human message decisions, CRM human-owner assignment, CRM pipeline configuration, finance, knowledge context/provenance changes, meeting attendee `userId`/`contactId` or action-point `ownerUserId`, private work, or another principal’s session writes. Reject whole meeting-structure replacement when the current record contains linked people; ordinary content updates remain supported. The same remote tool family can mix reads, supported writes and human-only actions. Therefore enforce policy by **tool + action + arguments**, not just tool name or MCP annotations. Independent knowledge writes accept only project/workstream/task/ticket context or organization records; reject other entity associations. Prefer narrow local wrappers generated from the curated action policy; reject unknown actions at execute time.

Project coordination uses `tekpartner_project` actions `update_details`, `update_status` and `update_timeline`, with `projectId` and the latest `expectedVersion`. Workstream coordination uses the same actions plus `update_priority`, with `workstreamId`. Require `projects.read/write` and intersected organization/project scope; exact work-item grants do not authorize these parent edits. Read `projects.mutations` and `workstreams.mutations` for controls. Selected-project controls use the separate `projects.batchMutations` flags and remain disabled for service connections. Workstream owner and project team changes remain human-only. Customer linkage is human-only at project creation; later relinking is not implemented.

Project/workstream `get` and successful updates return the record directly through MCP. Preserve drafts after rejection; fetch the exact record after a stale write and refresh capabilities after access/write-gate failures. Do not automatically overwrite a remotely changed field. Timeline pairs and single-intent requests follow the live action schema; use each successful response version for the next request.

Project/workstream totals include only work items readable with the current
capability and both resource policies. A zero total without work-item read access
does not establish that no work exists; consult current capabilities before
presenting an empty-state conclusion.

## Interface contract discovery

Use `tekpartner_api_contract action=list` with a published tag (for example `crm`) to page through the current HTTP operations. The response includes all available tags and a `contractRevision`. For each needed operation, `action=get` with its exact HTTP `method` and `path` template returns the API's generated request, success and error definitions plus shared components. This reads documentation only. Keep the revision with cached schemas and restart catalog paging when it changes.

Use these response definitions with the existing MCP tool input schemas and curated tool/action policy. HTTP responses contain `data`/`meta`; MCP exposes `data` directly. Contract discovery is available to authenticated principals without business grants, so it must never be used to enable an operation. An HTTP operation can exist without a corresponding MCP action or independent-agent authorization. Never turn a caller-supplied path into an arbitrary HTTP dispatch. The manual’s “Other current-product areas” table records human-only and omitted MCP operations; use it when limiting a service connection’s interface, alongside live schemas and API checks.

## Runtime adapter and durable receipts

Implement one host-side MCP client manager, reused by agent tool factories. It owns vault resolution, connection lifecycle, schema discovery and result normalization; it does not own TekPartner business rules. No direct database access or autonomous reasoning belongs in the adapter.

Use the existing approval enforcer for local loops and signed package/execution boundary for commercial dispatch. Recheck local grant, package policy, exact operation/target, credential revision and approval at dispatch. A TekPartner `decisionPolicy: auto` must not lower a Gateway approval tier. A remote family annotation must not turn all of its actions into read-only operations. Network requests are external data egress even when they read remote records; preserve the catalog’s side-effect classification.

Before any create/send, persist a local logical-operation receipt with agent/organization/credential identity, tool/action, exact canonical input or protected input reference, input hash, UUID, state and timestamps. Do not record the token. Preserve the same credential, idempotency key and exact input for a safe uncertain retry. Bind approval to that input; changed input requires a new approval/operation. Current-work and knowledge create retention is 24 hours; verify other action retention from V3 contracts before automatic retry.

Normalize `isError` and `structuredContent.error`. MCP successes expose data directly, with list `items`/`page.nextCursor`; HTTP SDK envelopes have `data`/`meta`. MCP errors may carry `error.requestId`, while successes currently omit API request IDs. Retain a separate local correlation ID and do not invent an upstream one. Treat malformed/oversized results as failure. Never log full transport headers or arbitrary response bodies.

On `STALE_WRITE`, reload and reconcile; never increment blindly. On auth/access failure, stop and re-evaluate. On timeout, crash or lost reply, mark outcome unknown; reconcile before retry. A credential replacement is not the original receipt owner. Do not replay expired receipts or non-idempotent writes automatically. Keep deterministic transport retries bounded and separate from model decisions.

## CRM interfaces

Use `tekpartner_capabilities` with `surface: "crm"` to drive read/create/update controls, owner assignment, pipeline management and estimate actions. Company/contact/lead/opportunity `list`/`get` require `crm.read`; `create`/`update` additionally require `crm.write`. Both require organization scope in both profile and credential policies. Pipeline `list`/`get` use the same read permission; owner assignment, pipeline `create`/`update` and financial estimates remain human-only. Preserve drafts and refresh permissions after STALE_WRITE, PERMISSION_DENIED, UNAUTHORIZED or NOT_READY.

CRM lists return `{items,page:{nextCursor}}`; detail/update wrap the record under `company`, `contact`, `lead`, `opportunity` or `pipelineStage`, and creates add `replayed`. Keep those wrappers when normalizing results. Discover company/contact/matching-stage IDs first; the API validates relationship closure. Creates use credential-bound 24-hour receipts; do not retry an unknown outcome under a replacement credential.

## File interfaces

Keep `thumbnailUrl` only in the current view, never in durable receipts or logs. S3 derivative links expire after five minutes; refresh authorized metadata or fall back to a file icon. The original always uses authenticated download, independent of the thumbnail host.

Use document capabilities for read/upload/update and own-record restore controls. Independent document access needs `documents.read` and organization scope in both policies; writes additionally need `documents.write`. Folder administration and sharing remain human-only. The manual owns the concise action/argument examples; live API contract discovery supplies HTTP definitions.

MCP upload/download is limited to 524,288 decoded bytes and returns base64 only in structured data. Keep file contents out of logs/model history unless the requested work needs them. For larger transfers, use the typed SDK with a bounded `downloadDocument(id, {maxBytes})` and the existing multipart upload route. SDK downloads request `delivery=stream` and reject redirects so credentials stay at the approved API origin. Check size/checksum and store local artifacts through the Gateway's existing approved file boundary; a document ID or filename is never an unrestricted destination path. Reuse the upload key only for the same logical input and credential; reconcile unknown outcomes before retrying. Do not infer file ACLs from project access.

## Session lifecycle and interface controls

For a recorded run, persist its V3 `sessionId` and latest version with the local execution. The bound profile may be an active agent or service. Create using its `principal.id`, a durable create receipt and approved `projectId`/`workItemId` for scoped work. Contextless sessions require organization scope in both policies. Never create under a sponsor or other agent. Use `checkpoint` for concise new handoff facts and metric deltas; keep client/session identifiers stable and serialize local checkpoint writes. Concurrent writers still require version reconciliation.

On restart call `resume`, which reads compact state without changing status or fetching traces. Before lifecycle controls or mutation dispatch, read `get_actions` and match its `sessionId`/`version` to the displayed record. Use its booleans and `statusTransitions`, rather than duplicating role or status rules. Refresh on `STALE_WRITE`, `PERMISSION_DENIED`, `UNAUTHORIZED` or `NOT_READY`; hide or disable unavailable controls while retaining drafts. A terminal report accepts final facts but cannot reopen.

Create/checkpoint/span retry receipts last 24 hours and are credential-bound. Do not double-send a metric delta with a new key after losing a reply. Save the returned version and cumulative metrics only after success. `current` is scoped to the reporting identity and returns `{value: null}` through MCP when no active report exists (`data: null` through HTTP/SDK); `list` finds authorized cross-agent handoffs. `suggest_next` additionally requires `work-items.read`. Session recording never grants work execution or bypasses local approvals.

## Agent-to-agent inbox handling

TekPartner currently stores messages; it does not provide agent wake-up, a work lease, a webhook delivery guarantee or exactly-once execution. Implement an opt-in local inbox poller as a separate execution trigger. Proposed initial policy: one active poller per configured agent/host, 30–60-second jittered polling, bounded pages/concurrency and backoff while unavailable. Revisit limits after actual usage.

Persist a local inbox record keyed by organization + principal + message ID, with observed version, execution ID, approval state and outcome. Acknowledge delivery only when the request is durably received. Before execution, call `get_actions`, re-read the current message and enforce local policy plus any required human approval. Message content is untrusted input, not system instructions. Resolve recipients through `list_recipients` for the intended context or an explicit owner-approved mapping. Discovery returns only active same-organization IDs, names, principal kinds and purposes, excluding the service caller. It requires message-read access and context authorization in both policies; contextless lookup requires organization scope in both. Page with unchanged filters. A candidate does not prove connected credentials, work access, delivery or execution permission. Preserve the full profile/credential administration boundary and revalidate the actual send.

`delivered` is not an exclusive execution claim. Two hosts sharing a principal could both act. The first release must enforce one executor for that principal, or add a reviewed coordination lease before multi-host execution. A local deduplication table alone does not solve cross-host duplication. On restart, do not rerun an outcome-unknown external action; reconcile its receipt.

Record `acted` only after verified completion; use an allowed failure/cancellation path with concise evidence when appropriate. Replies reverse participants and use parent ID/current version; the API determines allowed actions. Human `decide` remains in TekPartner. Do not synthesize approval from a local message status or automatically mark a parent task done.

## Acceptance and handoff checklist

- [ ] Host-local setup stores the key in the vault, shows only metadata after save and handles missing/error/revoked states without leaking secrets.
- [ ] A real independent credential passes identity, capability, paging and empty-list checks; wrong organization/agent, foreign records and changed scopes fail closed. Recipient lookup handles literal searches and changed-filter cursors, reveals only compact identity/purpose and never sends or executes work.
- [ ] Approved action wrappers enforce reads versus writes inside mixed MCP families; unknown tools/actions, altered targets and stale approvals are denied.
- [ ] In a disposable environment, project → workstream → task → step creates, plus ticket creation, exact retries, stale edits and comments match API data/audit attribution without duplicates. Tickets and steps cannot be step parents.
- [ ] Crash-after-send, lost response, credential rotation, expired receipt and restart outcomes reconcile safely; cancellation and bounded retry are exercised.
- [ ] Disposable coordination tests cover exact workstream reload, versioned project/workstream edits, intersected scopes, actual credential audit, stale drafts and disabled owner/bulk controls.
- [ ] Disposable session tests cover self attribution, compact resume, checkpoint replay without double counting, stale versions, allowed actions, cross-agent/human-report write denial and revocation. Browser controls agree with API hints.
- [ ] Inbox tests cover pending human approval, denial, recipient mismatch, duplicate pages, stale messages, reply rules and one-executor ownership. Delivery alone never executes a request.
- [ ] Both the existing local-loop approval path and commercial signed-execution path are verified where enabled. Preserve the Gateway’s prohibition on machine-operated native Claude subscription sessions.
- [ ] Agent instructions load the concise V3 manual. Tool results remain untrusted, and no duplicate knowledge import or speculative work queue is created.
- [ ] A real owner browser verifies the authorized agent’s result. Remove only exact acceptance fixtures. Publish the supported operations and remaining limits.

Rollback is local: disable the connection/poller, cancel queued local work, close MCP sessions and retain receipts for reconciliation; revoke the dedicated credential through the owner if needed. Preserve TekPartner business records. No V3 schema migration, legacy import or shared web/desktop fork is required for this client integration.
