@mastra/mcp-docs-server 1.1.49-alpha.1 → 1.2.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,124 @@
1
+ # Modes
2
+
3
+ Modes define the different behaviors a Harness can run. Each mode layers its own instructions and tool overrides on top of a shared backing agent, so the same agent can act as a planner in one mode and an executor in another. The Harness keeps exactly one mode active at a time, carries the thread and state across switches, and handles the transition between them.
4
+
5
+ Every Harness needs at least one mode — the `modes` array is required, and the Harness throws at construction if it's empty. A single-purpose Harness still defines one mode; multiple modes are how you give a session more than one behavior to switch between.
6
+
7
+ A mode supplies three things that change how the agent behaves:
8
+
9
+ - **Instructions**: layered on top of the backing agent's own instructions while the mode is active.
10
+ - **Tools**: either replacing or adding to the backing agent's tools (see [Mode tool overrides](#mode-tool-overrides)).
11
+ - **Model**: an optional `defaultModelId` to bootstrap model selection when the session enters the mode.
12
+
13
+ Because every mode shares the same backing agent, thread, and state, switching modes changes how the agent behaves without losing conversation context.
14
+
15
+ ## Quickstart
16
+
17
+ Import the `Harness` class and create a new instance with your agent and modes:
18
+
19
+ ```typescript
20
+ import { Harness } from '@mastra/core/harness'
21
+ import { myAgent } from './agents'
22
+
23
+ const harness = new Harness({
24
+ id: 'multi-mode',
25
+ agent: myAgent,
26
+ modes: [
27
+ {
28
+ id: 'plan',
29
+ name: 'Plan',
30
+ metadata: { default: true },
31
+ instructions: 'Reason about the task before making changes.',
32
+ },
33
+ { id: 'build', name: 'Build', instructions: 'Implement the approved plan.' },
34
+ ],
35
+ })
36
+
37
+ await harness.init()
38
+ ```
39
+
40
+ ## Defining modes
41
+
42
+ Each mode requires an `id`. When a top-level `agent` is provided, modes layer instructions and tool overrides on the shared agent. Each mode can also specify a `defaultModelId` to bootstrap model selection:
43
+
44
+ ```typescript
45
+ import { Harness } from '@mastra/core/harness'
46
+
47
+ const harness = new Harness({
48
+ id: 'multi-mode',
49
+ agent: myAgent,
50
+ modes: [
51
+ {
52
+ id: 'plan',
53
+ name: 'Plan',
54
+ metadata: { default: true },
55
+ defaultModelId: 'anthropic/claude-sonnet-4-6',
56
+ instructions: 'Reason about the task before making changes.',
57
+ },
58
+ {
59
+ id: 'build',
60
+ name: 'Build',
61
+ defaultModelId: 'anthropic/claude-sonnet-4-6',
62
+ instructions: 'Implement the approved plan.',
63
+ },
64
+ ],
65
+ })
66
+ ```
67
+
68
+ ### Mode tool overrides
69
+
70
+ Modes support two strategies for tool configuration. Use `tools` to replace the backing agent's tools entirely, or `additionalTools` to layer extra tools on top:
71
+
72
+ ```typescript
73
+ // Replace — agent sees only these tools in plan mode
74
+ const planMode = { id: 'plan', tools: { planTool } }
75
+
76
+ // Augment — agent keeps its own tools plus these
77
+ const buildMode = { id: 'build', additionalTools: { deployTool } }
78
+ ```
79
+
80
+ You can't set both `tools` and `additionalTools` on the same mode.
81
+
82
+ ### Mode transitions
83
+
84
+ A mode can declare a `transitionsTo` target. When the `submit_plan` built-in tool runs in that mode, the Harness transitions to the target mode on approval:
85
+
86
+ ```typescript
87
+ const planMode = {
88
+ id: 'plan',
89
+ name: 'Plan',
90
+ transitionsTo: 'build',
91
+ instructions: 'Reason about the task and submit a plan.',
92
+ }
93
+ ```
94
+
95
+ On plan approval, the Harness automatically switches to `build` mode. On rejection, the agent remains in `plan` mode to revise.
96
+
97
+ ## Switching modes
98
+
99
+ Call `switchMode()` to change the active mode. The Harness aborts any in-progress generation, saves the current model to the outgoing mode, loads the incoming mode's model, and emits `mode_changed` and `model_changed` events:
100
+
101
+ ```typescript
102
+ await harness.switchMode({ modeId: 'build' })
103
+ ```
104
+
105
+ ## Querying modes
106
+
107
+ The Harness exposes the full mode catalog, while the Session tracks which mode is active. Use `harness.listModes()` to read every configured mode, `harness.session.mode.get()` for the active mode ID, and `harness.session.mode.resolve()` for the active mode's full definition:
108
+
109
+ ```typescript
110
+ // List all configured modes
111
+ const modes = harness.listModes()
112
+
113
+ // Get the current mode ID
114
+ const modeId = harness.session.mode.get()
115
+
116
+ // Get the full mode object
117
+ const mode = harness.session.mode.resolve()
118
+ ```
119
+
120
+ ## Related
121
+
122
+ - [Harness overview](https://mastra.ai/docs/harness/overview)
123
+ - [Threads and state](https://mastra.ai/docs/harness/threads-and-state)
124
+ - [API reference](https://mastra.ai/reference/harness/harness-class)
@@ -0,0 +1,130 @@
1
+ # Harness overview
2
+
3
+ > **Alpha:** The `Harness` feature is in alpha stage and subject to breaking changes in minor versions until it graduates from its alpha status.
4
+
5
+ The Harness is a session controller for building interactive agent applications. It handles the runtime concerns that sit between your UI and the agent loop: managing conversation threads, switching between agent modes, persisting state, gating tool execution with approvals, and coordinating subagents. You can focus on what your agent does rather than how to wire it together.
6
+
7
+ A Harness exposes a [`Session`](https://mastra.ai/docs/harness/session) — the per-conversation runtime state that tracks the active mode, model, thread binding, permission grants, follow-up queue, and token usage. The Harness is the shared host; the Session is the conversation running inside it. In a multi-user host, the same Harness can back many Sessions at once.
8
+
9
+ [Mastra Code](https://code.mastra.ai/) is the flagship Harness implementation: A terminal-based coding agent with multi-model support, persistent conversations, and plan-then-execute workflows.
10
+
11
+ ## What you can build
12
+
13
+ The Harness gives you the runtime pieces to ship interactive agent applications. Each outcome below maps to a capability you can use today:
14
+
15
+ - **Resume a conversation exactly where the user left off.** Persistent [threads and state](https://mastra.ai/docs/harness/threads-and-state) reload the active mode, model, and progress across restarts, so a coding agent or assistant picks up mid-task instead of starting over.
16
+ - **Gate destructive actions behind human approval.** [Tool approvals and permission policies](https://mastra.ai/docs/harness/tool-approvals) let you require confirmation for risky operations like file writes or deployments, while trusted tools run automatically.
17
+ - **Move a task through distinct phases without losing context.** [Modes](https://mastra.ai/docs/harness/modes) switch the agent's instructions, tools, and model on the same thread, so you can build a plan-then-execute coding agent or a research-then-draft assistant.
18
+ - **Let users pick the right model for each step.** Per-mode [model management](https://mastra.ai/reference/harness/harness-class) switches models at runtime and tracks usage, which powers copilot UIs where users trade speed for capability.
19
+ - **Delegate focused work to child agents.** [Subagents](https://mastra.ai/docs/harness/subagents) run subtasks with constrained tools and can fork the parent conversation, so a research mode can spin off web search or code review without polluting the main thread.
20
+ - **Drive a live UI from agent activity.** The [event system](https://mastra.ai/docs/harness/session) emits typed events and coalesced display snapshots, so your TUI or web app reflects message updates, mode changes, and pending approvals in real time.
21
+ - **Run long-lived autonomous agents.** Structured task lists, heartbeat handlers, and observational memory keep background task runners on track and let them learn across threads.
22
+
23
+ ## When to use the Harness
24
+
25
+ Use the Harness when your application needs:
26
+
27
+ - Multiple agent modes that share one conversation thread (e.g., plan → build → review)
28
+ - A control layer between your UI and the agent loop (model switching, state persistence, thread management)
29
+ - Tool approval flows and permission policies for human-in-the-loop gating
30
+ - Subagent orchestration to delegate focused subtasks with constrained tools
31
+ - Session continuity with persistent threads, state, and observational memory across restarts
32
+
33
+ You could assemble all of this yourself on top of the [Agent class](https://mastra.ai/docs/agents/overview), which exposes the full agent loop, tools, and memory. The Harness is an opinionated set of defaults that wires those pieces into one application style: an ongoing session where the agent acts as a collaborator rather than a one-shot endpoint. Reach for the Agent class directly when you want full control or a simple request-response call; reach for the Harness when you want the collaborative-session model without building the runtime around it.
34
+
35
+ ## Key capabilities
36
+
37
+ - **Session**: Per-conversation state — active thread, mode, model, grants, follow-ups, token usage, and the display snapshot — accessed through `harness.session`. See [Session](https://mastra.ai/docs/harness/session).
38
+ - **Modes**: Define distinct agent personalities (instructions, tools, model) and switch between them without losing conversation context. See [Modes](https://mastra.ai/docs/harness/modes).
39
+ - **Threads and state**: Persist conversations and structured state across sessions, users, and mode switches. See [Threads and state](https://mastra.ai/docs/harness/threads-and-state).
40
+ - **Subagents**: Spawn focused child agents with constrained tools for subtasks, optionally forking the parent conversation. See [Subagents](https://mastra.ai/docs/harness/subagents).
41
+ - **Tool approvals and permissions**: Configure which tools require user confirmation, grant session-wide exceptions, and handle interactive tool suspension. See [Tool approvals](https://mastra.ai/docs/harness/tool-approvals).
42
+ - **Model management**: Switch models per-mode at runtime, track usage, and resolve gateway-backed models through Mastra's [model router](https://mastra.ai/models).
43
+ - **Follow-ups and steering**: Queue messages while the agent is running, or inject mid-stream instructions to redirect the agent. Built on [signals](https://mastra.ai/docs/agents/signals).
44
+ - **Event system**: Subscribe to typed events (message updates, mode changes, tool approvals) or coalesced `HarnessDisplayState` snapshots to drive your UI. See [Events](https://mastra.ai/reference/harness/harness-class).
45
+ - **Observational memory**: Automatic summarization and reflection across threads for long-running agent sessions. See [Observational memory](https://mastra.ai/docs/memory/observational-memory).
46
+
47
+ ## Quickstart
48
+
49
+ Import the `Harness` class and create a new instance with an agent, storage backend, and modes:
50
+
51
+ ```typescript
52
+ import { Agent } from '@mastra/core/agent'
53
+ import { Harness } from '@mastra/core/harness'
54
+ import { LibSQLStore } from '@mastra/libsql'
55
+
56
+ const agent = new Agent({
57
+ name: 'assistant',
58
+ instructions: 'Help the user plan and complete tasks.',
59
+ model: 'openai/gpt-5.5',
60
+ })
61
+
62
+ const harness = new Harness({
63
+ id: 'my-agent',
64
+ agent,
65
+ storage: new LibSQLStore({ url: 'file:./data.db' }),
66
+ modes: [
67
+ {
68
+ id: 'plan',
69
+ name: 'Plan',
70
+ metadata: { default: true },
71
+ instructions: 'Reason about changes before making them.',
72
+ },
73
+ { id: 'build', name: 'Build', instructions: 'Implement the approved plan.' },
74
+ ],
75
+ })
76
+
77
+ harness.subscribe(event => {
78
+ if (event.type === 'message_update') {
79
+ console.log(event.message)
80
+ }
81
+ })
82
+
83
+ await harness.init()
84
+ await harness.selectOrCreateThread()
85
+ await harness.sendMessage({ content: 'Hello!' })
86
+ ```
87
+
88
+ > **Note:** Visit the [Harness reference](https://mastra.ai/reference/harness/harness-class) for the full constructor parameters and method signatures.
89
+
90
+ ## Architecture
91
+
92
+ The Harness sits between your application layer and the underlying agent loop:
93
+
94
+ ```text
95
+ ┌──────────────────────────┐
96
+ │ Your App (TUI/Web/API) │
97
+ └────────────┬─────────────┘
98
+ │ commands (sendMessage, switchMode, approve)
99
+ │ events (message_update, tool_approval_required)
100
+ ┌────────────▼─────────────┐
101
+ │ Harness (shared host) │
102
+ │ Config · Storage │
103
+ │ Thread lifecycle │
104
+ │ Permission policy │
105
+ │ Subagent spawning │
106
+ │ Event bus │
107
+ │ ┌─────────────────────┐ │
108
+ │ │ harness.session │ │
109
+ │ │ identity · thread │ │
110
+ │ │ mode · model · run │ │
111
+ │ │ grants · follow-ups │ │
112
+ │ │ display state │ │
113
+ │ └─────────────────────┘ │
114
+ └────────────┬─────────────┘
115
+
116
+ ┌────────────▼──────────────┐
117
+ │ Agent + Memory + Tools │
118
+ └───────────────────────────┘
119
+ ```
120
+
121
+ Your app sends commands (send a message, switch mode, approve a tool call) and receives typed events. The Harness manages the lifecycle internally: persisting threads, routing to the correct mode agent, enforcing permissions, and emitting events as state changes.
122
+
123
+ ## Next steps
124
+
125
+ - [Session](https://mastra.ai/docs/harness/session): The per-conversation state on a Harness
126
+ - [Modes](https://mastra.ai/docs/harness/modes): Define and switch between agent personalities
127
+ - [Threads and state](https://mastra.ai/docs/harness/threads-and-state): Manage persistent conversations
128
+ - [Subagents](https://mastra.ai/docs/harness/subagents): Delegate focused subtasks
129
+ - [Tool approvals and permissions](https://mastra.ai/docs/harness/tool-approvals): Human-in-the-loop gating
130
+ - [API reference](https://mastra.ai/reference/harness/harness-class): Full constructor and method docs
@@ -0,0 +1,139 @@
1
+ # Session
2
+
3
+ A [`Session`](https://mastra.ai/reference/harness/session) holds the live state of a Harness: who the session is for, which thread is active, the selected mode and model, permission grants, queued follow-ups, token usage, application state, and the display snapshot. You reach it through `harness.session`.
4
+
5
+ ## What the Session tracks
6
+
7
+ The Session is the live state of a single user's interaction with the Harness. It answers "what is true right now": who the session belongs to, which thread is currently bound, which mode and model are selected, what the user has approved, what's queued or running, the application state, and the snapshot to render. A session has one active thread at a time but can list, switch between, and clone many threads over its lifetime. Anything that describes the current state lives here; the Harness owns the shared infrastructure every session runs on.
8
+
9
+ Because each session has its own identity and state, one Harness can serve many users at once — each backed by its own Session — without one session's mode, grants, or active thread leaking into another.
10
+
11
+ The rest of this page walks through the Session's state. Each part is a focused sub-object on `harness.session`:
12
+
13
+ - **Who and where**: [Identity](#identity) sets the resource the session belongs to, and [Thread](#thread) tracks the currently bound thread.
14
+ - **How the agent behaves**: [Mode and model](#mode-and-model) controls which agent profile and model are active, and [Permission grants](#permission-grants) records what the user has approved to run without prompting.
15
+ - **What's happening right now**: [Run state](#run-state) reflects the in-flight generation, and [Follow-ups](#follow-ups) holds messages queued to send when it finishes.
16
+ - **What you store and render**: [State](#state) holds your application's structured data, and [Display state](#display-state) is the single snapshot your UI renders from.
17
+
18
+ The Harness performs actions that change this state — switching threads, modes, or models — because those operations coordinate shared infrastructure and emit events. The Session is where you read the result. The sections below note this split where it matters.
19
+
20
+ ## Identity
21
+
22
+ `session.identity` holds the resource ID the conversation belongs to and the currently bound thread ID. Threads are scoped to a resource ID, so this is what groups a conversation's threads together:
23
+
24
+ ```typescript
25
+ const resourceId = harness.session.identity.getResourceId()
26
+ const threadId = harness.session.thread.getId()
27
+ ```
28
+
29
+ The resource ID is set on the Harness constructor and defaults to the harness `id`. See [Resource IDs](https://mastra.ai/docs/harness/threads-and-state) for how it scopes threads.
30
+
31
+ ## Thread
32
+
33
+ `session.thread` owns the active thread binding and read access to threads and messages. The Harness performs lifecycle transitions; the Session reads the result:
34
+
35
+ ```typescript
36
+ // Lifecycle transitions live on the Harness
37
+ await harness.switchThread({ threadId: 'thread-abc123' })
38
+
39
+ // Reads live on the Session
40
+ const threads = await harness.session.thread.list()
41
+ const messages = await harness.session.thread.listActiveMessages()
42
+ ```
43
+
44
+ See [Threads and state](https://mastra.ai/docs/harness/threads-and-state) for the full lifecycle.
45
+
46
+ ## Mode and model
47
+
48
+ The Harness defines the available modes in `config.modes`. The Session tracks which mode and model are _currently_ selected:
49
+
50
+ ```typescript
51
+ // Switch mode (Harness orchestration — aborts the run, emits events)
52
+ await harness.switchMode({ modeId: 'build' })
53
+
54
+ // Read the current selection (Session state)
55
+ const modeId = harness.session.mode.get()
56
+ const mode = harness.session.mode.resolve()
57
+ const modelId = harness.session.model.get()
58
+ ```
59
+
60
+ See [Modes](https://mastra.ai/docs/harness/modes) for how modes carry their own model.
61
+
62
+ ## Permission grants
63
+
64
+ The Harness owns permission _policy_ — which categories or tools require approval. The Session owns the _grants_ a user makes during the conversation. A grant lets a tool run for the rest of the session without prompting again:
65
+
66
+ ```typescript
67
+ // Grant a category or tool for the rest of the session
68
+ harness.session.grantCategory('edit')
69
+ harness.session.grantTool('mastra_workspace_execute_command')
70
+
71
+ // Inspect current grants
72
+ const grants = harness.session.getGrants()
73
+ ```
74
+
75
+ Grants are intentionally in-memory and reset when the session restarts. See [Tool approvals](https://mastra.ai/docs/harness/tool-approvals) for the approval flow.
76
+
77
+ ## Run state
78
+
79
+ `session.run` tracks the in-flight generation: whether a run is active, its run and trace IDs, and the abort signal. Use it to reflect run status in your UI:
80
+
81
+ ```typescript
82
+ if (harness.session.run.isRunning()) {
83
+ // show a stop button
84
+ }
85
+
86
+ // Abort the active run (Harness orchestration clears related state)
87
+ harness.abort()
88
+ ```
89
+
90
+ ## Follow-ups
91
+
92
+ A user may want to add to the conversation while the agent is still working. Instead of dropping or interrupting those messages, the Session queues them on `session.followUps` and sends them when the current run finishes:
93
+
94
+ ```typescript
95
+ const queued = harness.session.followUps.count()
96
+ ```
97
+
98
+ Queue a follow-up with `harness.followUp({ content })`. To redirect the agent mid-run instead of waiting, use `harness.steer({ content })`. Both build on [signals](https://mastra.ai/docs/agents/signals).
99
+
100
+ ## State
101
+
102
+ `session.state` holds the conversation's application state — structured values that agents and the UI share, such as model preferences, feature flags, or progress. The Harness defines the shape with a `stateSchema`; the Session owns the live snapshot, validates updates against the schema, and emits `state_changed` on every write:
103
+
104
+ ```typescript
105
+ const state = harness.session.state.get()
106
+ await harness.session.state.set({ theme: 'light' })
107
+ ```
108
+
109
+ See [Threads and state](https://mastra.ai/docs/harness/threads-and-state) for defining a schema.
110
+
111
+ ## Display state
112
+
113
+ A conversation emits many fine-grained events: tokens streaming in, tools starting and finishing, approvals pending, tasks updating, token usage climbing. Subscribing to each event type and reassembling the current picture yourself is tedious and error-prone. `session.displayState` does that work for you.
114
+
115
+ It's a reducer-maintained snapshot. The Session keeps one `HarnessDisplayState` object and folds every harness event into it as it happens, so the snapshot always reflects the latest state. It captures everything a UI needs to render: whether the agent is running and what it's streaming, which tools and subagents are active, anything waiting on the user such as approvals, the current task list, and running totals like token usage and queued follow-ups.
116
+
117
+ Because it's a single object, you can drive an entire UI from one place: read the current snapshot with `get()`, and re-render whenever the Harness emits `display_state_changed` (fired after every other event):
118
+
119
+ ```typescript
120
+ const snapshot = harness.session.displayState.get()
121
+
122
+ // Re-render from the snapshot on every change
123
+ harness.subscribe(event => {
124
+ if (event.type === 'display_state_changed') {
125
+ render(harness.session.displayState.get())
126
+ }
127
+ })
128
+ ```
129
+
130
+ This is the recommended pattern for most UIs. Subscribe to individual typed events only when you need to react to a specific transition rather than re-render the whole view.
131
+
132
+ > **Note:** Visit the [Session reference](https://mastra.ai/reference/harness/session) for the full list of sub-objects and method signatures.
133
+
134
+ ## Related
135
+
136
+ - [Harness overview](https://mastra.ai/docs/harness/overview)
137
+ - [Threads and state](https://mastra.ai/docs/harness/threads-and-state)
138
+ - [Tool approvals](https://mastra.ai/docs/harness/tool-approvals)
139
+ - [Session reference](https://mastra.ai/reference/harness/session)
@@ -0,0 +1,104 @@
1
+ # Subagents
2
+
3
+ Subagents let a parent agent delegate focused tasks to child agents with constrained tools and instructions. The Harness auto-generates a `subagent` built-in tool that the parent model can call to spawn any configured subagent type. Reach for a subagent when a task needs a different toolset or instruction set than the parent agent, when you want to isolate a subtask's messages from the parent thread, or when the parent should delegate to a cheaper or faster model for specific work.
4
+
5
+ ## Quickstart
6
+
7
+ Define subagent types in the Harness constructor:
8
+
9
+ ```typescript
10
+ import { Agent } from '@mastra/core/agent'
11
+ import { Harness } from '@mastra/core/harness'
12
+
13
+ const agent = new Agent({
14
+ name: 'assistant',
15
+ instructions: 'Use subagents when a focused task needs a narrower toolset.',
16
+ model: 'openai/gpt-5.5',
17
+ })
18
+
19
+ const harness = new Harness({
20
+ id: 'with-subagents',
21
+ agent,
22
+ modes: [{ id: 'default', name: 'Default', metadata: { default: true } }],
23
+ subagents: [
24
+ {
25
+ id: 'explore',
26
+ name: 'Explore',
27
+ description: 'Reads files and gathers context without making changes.',
28
+ instructions: 'You are a read-only exploration agent.',
29
+ allowedWorkspaceTools: ['read_file', 'list_directory', 'grep_search'],
30
+ defaultModelId: 'anthropic/claude-haiku-4-5',
31
+ maxSteps: 30,
32
+ },
33
+ {
34
+ id: 'execute',
35
+ name: 'Execute',
36
+ description: 'Makes changes to files and runs commands.',
37
+ instructions: 'You are an execution agent.',
38
+ allowedWorkspaceTools: ['read_file', 'write_file', 'execute_command'],
39
+ defaultModelId: 'anthropic/claude-sonnet-4-6',
40
+ },
41
+ ],
42
+ })
43
+ ```
44
+
45
+ The parent agent can then call the auto-generated `subagent` tool with a `task` description and optional `agentType`.
46
+
47
+ When you define a subagent, write its `description` and `instructions` to be clear and narrow. The `description` is what the parent model reads to decide _when_ to delegate, so state the single job the subagent is for and, by implication, what it's not for — "Reads files and gathers context without making changes" tells the parent to reach for it during exploration and to handle edits elsewhere. The `instructions` then keep the child agent inside that job. A subagent scoped to one task with a focused toolset stays predictable and is easier for the parent to route to; a broadly described subagent invites the parent to over-delegate and blurs the boundary between types. Pair the narrow scope with `allowedWorkspaceTools` so the subagent can only do what its description promises.
48
+
49
+ For the full list of subagent configuration options, see [`Harness` reference](https://mastra.ai/reference/harness/harness-class).
50
+
51
+ ## Forked subagents
52
+
53
+ A default subagent starts with a fresh context: it can't see the parent conversation, so you pass everything it needs in the `task` description. That's the right model for self-contained work, but it has two costs. The subagent has no access to what's already happened, and it builds a brand-new request prefix — a different system prompt and tool schemas — so it can't reuse the parent's prompt cache.
54
+
55
+ **Forked subagents** solve both. Instead of a fresh agent, a fork clones the parent thread and runs the parent agent itself, so it sees the full conversation history and keeps the same system prompt and tool schemas as the parent. The identical prefix means the model's prompt cache still hits, which makes context-heavy delegation cheaper and faster.
56
+
57
+ Use a fork when the subtask depends on the conversation so far — prior messages, earlier tool results, or the parent's tool environment — and you want to run it without paying to rebuild that context. Use a default subagent when the task is self-contained and benefits from a narrower toolset, a tighter system prompt, or a cheaper model.
58
+
59
+ Enable forked mode per-type:
60
+
61
+ ```typescript
62
+ const collaborator = {
63
+ id: 'collaborator',
64
+ name: 'Collaborator',
65
+ description: 'Continues the conversation in a fork.',
66
+ forked: true,
67
+ }
68
+ ```
69
+
70
+ Or per-invocation via the `subagent` tool's `forked` input parameter, which overrides the type's default.
71
+
72
+ ### Forked mode semantics
73
+
74
+ Because a fork reuses the parent agent to keep the prompt prefix stable, the subagent's own definition is mostly set aside:
75
+
76
+ - Memory must be configured on the Harness, since forking clones the parent thread. Without it, the fork call returns an error.
77
+ - The fork runs with the parent agent's instructions, tools, and model. The subagent definition's own `instructions`, `tools`, and `defaultModelId` are ignored, and a per-invocation `modelId` is ignored too.
78
+ - Only the subagent definition's `description` still matters — it's what the parent model reads to decide when to delegate.
79
+ - Fork threads are tagged with `metadata.forkedSubagent === true` and hidden from `session.thread.list()` by default.
80
+ - Recursive forks are blocked at runtime: the inherited `subagent` tool is disabled inside a fork to prevent infinite nesting.
81
+
82
+ ## Subagent model management
83
+
84
+ Set a global or per-type subagent model at runtime:
85
+
86
+ ```typescript
87
+ // Global subagent model
88
+ await harness.setSubagentModelId({ modelId: 'anthropic/claude-sonnet-4-6' })
89
+
90
+ // Per-type override
91
+ await harness.setSubagentModelId({
92
+ modelId: 'anthropic/claude-haiku-4-5',
93
+ agentType: 'explore',
94
+ })
95
+
96
+ // Read current model
97
+ const modelId = harness.getSubagentModelId({ agentType: 'explore' })
98
+ ```
99
+
100
+ ## Related
101
+
102
+ - [Harness overview](https://mastra.ai/docs/harness/overview)
103
+ - [Tool approvals and permissions](https://mastra.ai/docs/harness/tool-approvals)
104
+ - [API reference](https://mastra.ai/reference/harness/harness-class)
@@ -0,0 +1,139 @@
1
+ # Threads and state
2
+
3
+ Threads and state are how a Harness conversation survives beyond a single exchange. A **thread** is the persistent record of a conversation — its messages and metadata, saved to storage so a user can close the app and resume the same conversation later, or switch between several conversations. **State** is structured data attached to the conversation — values like model preferences, feature flags, or progress — that agents and your UI read and write as the conversation runs.
4
+
5
+ The two work together: the thread is the message history, and state is the shared scratchpad alongside it. Both persist across mode switches, model changes, and restarts, so nothing is lost when a user switches from plan mode to build mode or reopens the app the next day.
6
+
7
+ Thread _lifecycle_ transitions — create, switch, clone, delete — live on the Harness because they coordinate the shared thread lock and emit events. The active thread binding and thread/message _reads_ live on the [`Session`](https://mastra.ai/docs/harness/session) as `harness.session.thread`.
8
+
9
+ ## Threads
10
+
11
+ A thread holds one conversation's full message history. The Harness binds the Session to one active thread at a time; messages you send and the agent's replies are appended to that thread and saved to storage. Threads let users resume a past conversation, keep several conversations side by side, or branch one into alternatives.
12
+
13
+ ### Creating and selecting threads
14
+
15
+ On startup, call `selectOrCreateThread()` to resume the most recent thread or create a new one:
16
+
17
+ ```typescript
18
+ await harness.init()
19
+ const thread = await harness.selectOrCreateThread()
20
+ ```
21
+
22
+ Create a thread explicitly with a title:
23
+
24
+ ```typescript
25
+ const thread = await harness.createThread({ title: 'New conversation' })
26
+ ```
27
+
28
+ ### Switching threads
29
+
30
+ Switch to an existing thread. The harness aborts any in-progress generation, acquires a lock on the new thread, and emits a `thread_changed` event:
31
+
32
+ ```typescript
33
+ await harness.switchThread({ threadId: 'thread-abc123' })
34
+ ```
35
+
36
+ ### Listing threads
37
+
38
+ List threads for the current resource. Forked subagent threads are hidden by default:
39
+
40
+ ```typescript
41
+ const threads = await harness.session.thread.list()
42
+
43
+ // Include all resources
44
+ const allThreads = await harness.session.thread.list({ allResources: true })
45
+ ```
46
+
47
+ ### Cloning threads
48
+
49
+ Clone a thread to create a branch of the conversation. The harness copies all messages and switches to the clone:
50
+
51
+ ```typescript
52
+ const cloned = await harness.cloneThread({ title: 'Alternative approach' })
53
+ ```
54
+
55
+ ### Thread locking
56
+
57
+ Pass a `threadLock` to the Harness constructor to prevent concurrent access from multiple processes. The lock is acquired before any thread operation and released on switch or delete:
58
+
59
+ ```typescript
60
+ const harness = new Harness({
61
+ id: 'my-agent',
62
+ threadLock: {
63
+ acquire: async threadId => {
64
+ /* acquire lock or throw */
65
+ },
66
+ release: async threadId => {
67
+ /* release lock */
68
+ },
69
+ },
70
+ })
71
+ ```
72
+
73
+ ## State
74
+
75
+ Where a thread stores the conversation's messages, state stores structured values that describe the conversation but aren't messages — model preferences, feature flags, UI settings, or progress markers. Agents can read and update state during a run, and your UI can react to changes, so state is how the agent and the interface stay in sync on shared facts. You define its shape with a schema, and every update is validated against that schema before it's applied.
76
+
77
+ ### Defining a state schema
78
+
79
+ Pass a `stateSchema` (Standard JSON Schema) to validate state and extract defaults:
80
+
81
+ ```typescript
82
+ import { Agent } from '@mastra/core/agent'
83
+ import { Harness } from '@mastra/core/harness'
84
+ import { z } from 'zod'
85
+
86
+ const agent = new Agent({
87
+ name: 'assistant',
88
+ instructions: 'Help the user manage a stateful session.',
89
+ model: 'openai/gpt-5.5',
90
+ })
91
+
92
+ const harness = new Harness({
93
+ id: 'stateful-agent',
94
+ agent,
95
+ modes: [{ id: 'default', name: 'Default', metadata: { default: true } }],
96
+ stateSchema: z.object({
97
+ currentModelId: z.string().optional(),
98
+ theme: z.enum(['light', 'dark']).default('dark'),
99
+ }),
100
+ })
101
+ ```
102
+
103
+ ### Reading and writing state
104
+
105
+ State is owned by the [`Session`](https://mastra.ai/docs/harness/session) as `harness.session.state`:
106
+
107
+ ```typescript
108
+ // Read the current state snapshot
109
+ const state = harness.session.state.get()
110
+
111
+ // Update state — validates against schema and emits state_changed
112
+ await harness.session.state.set({ theme: 'light' })
113
+ ```
114
+
115
+ State changes emit a `state_changed` event with the new state and the set of changed keys.
116
+
117
+ ## Resource IDs
118
+
119
+ Threads are scoped to a resource ID, which groups a conversation's threads by project, user, or workspace. Set it on the Harness constructor; it defaults to the harness `id` when omitted:
120
+
121
+ ```typescript
122
+ const harness = new Harness({
123
+ id: 'my-agent',
124
+ resourceId: 'project-xyz',
125
+ })
126
+ ```
127
+
128
+ The resource ID is part of a conversation's identity, so you read it from the Session:
129
+
130
+ ```typescript
131
+ const resourceId = harness.session.identity.getResourceId()
132
+ ```
133
+
134
+ ## Related
135
+
136
+ - [Harness overview](https://mastra.ai/docs/harness/overview)
137
+ - [Session](https://mastra.ai/docs/harness/session)
138
+ - [Modes](https://mastra.ai/docs/harness/modes)
139
+ - [API reference](https://mastra.ai/reference/harness/harness-class)