uring execution.
import { MCPClient } from '@anthropic-ai/mcp-host';
const mcpConfig = {
servers: [
{
name: 'local-storage',
transport: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', './shared-state']
},
{
name: 'document-store',
transport: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-google-drive']
},
{
name: 'communication-channel',
transport: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-gmail']
},
{
name: 'web-intel',
transport: 'stdio',
command: 'npx',
args: ['-y', 'brave-search-mcp']
}
]
};
const mcpHost = new MCPClient(mcpConfig);
await mcpHost.initialize();
Rationale: Using stdio transport keeps the architecture lightweight and avoids network overhead during early deployment. The shared-state directory is explicitly mounted to the filesystem server, ensuring all agents read and write to the same atomic location.
Each agent receives a specialized system prompt, a bounded toolset, and an execution schema. This prevents cross-contamination of capabilities and enforces domain boundaries.
interface AgentDefinition {
id: string;
role: string;
systemPrompt: string;
allowedTools: string[];
executionLoop: () => Promise<void>;
}
const marketIntelAgent: AgentDefinition = {
id: 'market-intel-v1',
role: 'competitive analyst',
systemPrompt: `You are a senior market intelligence analyst.
Monitor competitive movements, track industry funding, and identify emerging threats.
Always reference the shared knowledge base before generating reports.
Every finding requires a verified source URL. Prioritize signal over noise.`,
allowedTools: ['local-storage', 'web-intel', 'document-store'],
executionLoop: async () => {
const previousBrief = await mcpHost.read('shared-state/market/weekly-brief-latest.md');
const searchResults = await mcpHost.callTool('web-intel', { query: 'competitor pricing changes last 7 days' });
const report = await mcpHost.generate({
model: 'claude-sonnet-4-20250514',
prompt: `Compile findings into structured brief. Compare against:\n${previousBrief}`,
tools: ['local-storage', 'web-intel']
});
await mcpHost.write('shared-state/market/weekly-brief-latest.md', report.content);
}
};
Rationale: Bounding allowedTools prevents the research agent from accidentally triggering email or calendar operations. The execution loop explicitly reads previous state before generating new output, enforcing temporal continuity and preventing duplicate reporting.
Step 3: Quality Gate Implementation
Autonomous content generation degrades without enforcement mechanisms. The content pipeline must include a scoring loop that validates output against brand parameters before allowing publication.
async function enforceQualityGate(draft: string, brandParams: Record<string, any>): Promise<string> {
let iteration = 0;
let currentDraft = draft;
while (iteration < 3) {
const evaluation = await mcpHost.generate({
model: 'claude-sonnet-4-20250514',
prompt: `Score this draft on a 0-10 scale for:
1. Voice alignment with brand parameters
2. Hook strength and retention probability
3. Value density per paragraph
4. Originality relative to industry baseline
Brand Parameters: ${JSON.stringify(brandParams)}
Draft: ${currentDraft}
Return JSON: { scores: { voice: number, hook: number, density: number, originality: number }, weakestSection: string }`
});
const scores = JSON.parse(evaluation.content).scores;
const minThreshold = 7;
if (Object.values(scores).every(s => s >= minThreshold)) {
return currentDraft;
}
const rewritePrompt = `Improve the weakest section: ${JSON.parse(evaluation.content).weakestSection}.
Maintain all other strengths. Output only the revised draft.`;
currentDraft = await mcpHost.generate({ model: 'claude-sonnet-4-20250514', prompt: rewritePrompt });
iteration++;
}
throw new Error('Quality gate failed after maximum iterations. Requires human review.');
}
Rationale: The loop caps at three iterations to prevent infinite refinement cycles. Failing the gate triggers a human-in-the-loop fallback rather than publishing substandard output. This pattern is critical for production deployments where brand reputation is at stake.
Step 4: Shared State Coordination
The three agents coordinate through a structured directory. Atomic file operations prevent race conditions, and explicit naming conventions enable deterministic reads.
shared-state/
βββ market/
β βββ alerts.md
β βββ weekly-brief-latest.md
βββ content/
β βββ drafts/
β βββ approved/
β βββ performance-metrics.json
βββ ops/
βββ contact-index.json
βββ meeting-history/
βββ weekly-summary.md
When the market agent detects a competitor pricing shift, it writes to market/alerts.md. The content pipeline reads this file during initialization and generates reactive drafts. The operational coordinator reads the same alert and drafts customer notification templates. This event-driven file system eliminates the need for complex message queues while maintaining full traceability.
Pitfall Guide
1. Unstructured Shared State
Explanation: Agents overwrite each other's outputs or read stale data because file naming lacks temporal or versioned conventions.
Fix: Enforce YYYY-MM-DD-domain-topic.md naming. Implement atomic writes using temporary files that are renamed only after successful completion.
2. Quality Gate Bypass
Explanation: Skipping the scoring loop to save API credits results in generic, off-brand output that damages credibility.
Fix: Hardcode the minimum threshold in the orchestration layer. Never allow publication without passing the gate. Log all failures for weekly review.
Explanation: Brave Search or Gmail MCP servers hit daily limits, causing silent failures or incomplete workflows.
Fix: Implement exponential backoff with jitter. Cache search results locally for 24 hours. Monitor quota usage via a lightweight metrics endpoint.
4. Prompt Drift Over Time
Explanation: System prompts lose effectiveness as context windows fill with historical data, causing inconsistent behavior.
Fix: Version prompts in a prompts/ directory. Run weekly A/B tests against baseline outputs. Rotate system prompts quarterly based on performance metrics.
5. Over-Automation of Critical Paths
Explanation: Auto-sending emails or publishing content without review leads to compliance risks or brand damage.
Fix: Route all high-impact actions through a human approval queue. Use the agent to draft and schedule, but require explicit confirmation before execution.
6. Missing Fallback Mechanisms
Explanation: Tool failures cause the entire workflow to halt without notification, leaving operators unaware of broken pipelines.
Fix: Wrap all MCP calls in try/catch blocks. Implement a dead-letter queue for failed executions. Send a summary alert to a monitoring channel when retries are exhausted.
7. Context Window Saturation
Explanation: Feeding entire knowledge bases into every prompt exceeds token limits and degrades reasoning quality.
Fix: Use semantic chunking for the shared state. Only inject relevant sections based on the current workflow phase. Maintain a lightweight index file for fast lookups.
Production Bundle
Action Checklist
Decision Matrix
| Scenario | Recommended Approach | Why | Cost Impact |
|---|
| Solo founder, low volume | File-based shared state + MCP | Zero infrastructure overhead, easy debugging | <$50/mo API credits |
| Small team, high volume | Vector DB + message queue | Faster retrieval, concurrent execution support | $150β300/mo infra + API |
| Compliance-heavy industry | Human-in-the-loop gate + audit logging | Regulatory safety, traceable decision paths | +20% operational latency |
| Rapid prototyping | Single agent + broad tool access | Fast iteration, minimal configuration | Low initial, scales poorly |
Configuration Template
{
"mcp_host": {
"version": "2.1",
"servers": [
{ "name": "local-storage", "path": "./shared-state" },
{ "name": "document-store", "scope": "readonly" },
{ "name": "communication-channel", "scope": "draft-only" },
{ "name": "web-intel", "rate_limit": "100/min" }
]
},
"agents": [
{
"id": "market-intel-v1",
"model": "claude-sonnet-4-20250514",
"tools": ["local-storage", "web-intel"],
"schedule": "0 7 * * 1",
"output_path": "shared-state/market/weekly-brief-latest.md"
},
{
"id": "content-pipeline-v1",
"model": "claude-sonnet-4-20250514",
"tools": ["local-storage", "web-intel"],
"quality_gate": { "min_score": 7, "max_iterations": 3 },
"output_path": "shared-state/content/approved/"
},
{
"id": "ops-coordinator-v1",
"model": "claude-sonnet-4-20250514",
"tools": ["local-storage", "communication-channel", "document-store"],
"schedule": "0 8 * * 1-5",
"approval_required": ["email-send", "calendar-modify"]
}
]
}
Quick Start Guide
- Install MCP Host: Run
npm install @anthropic-ai/mcp-host and initialize the configuration file with the template above.
- Mount Shared State: Create the
shared-state/ directory structure and grant read/write permissions to the filesystem MCP server.
- Register Agents: Define the three agent objects in your orchestration script, binding each to its allowed tools and execution loop.
- Schedule Execution: Use a cron scheduler or the host's native trigger system to run agents at defined intervals. Verify tool connectivity with a dry-run execution.
- Monitor & Iterate: Check the first three execution cycles for tool failures, quality gate passes, and state consistency. Adjust prompts and thresholds based on output metrics.