Autonomous AI Agents + MCP Protocol + LangGraph 2026 + pgvector
Ironclad behavioral invariants for autonomous AI agents, Model Context Protocol (MCP) tool servers, durable LangGraph state machines, and high-recall PostgreSQL pgvector HNSW indexing.
Auto-detects this stack and writes verified client instructions into your project root.
# Combined .cursorrules generated by AgentRules.org (https://agentrules.org)
# Specification Version: 2026.10-Industrial | Licensed under CC BY 4.0
# Stack: Model Context Protocol (MCP) TypeScript SDK Standard, Python FastMCP Protocol & Tool Server Standard, LangGraph 2026 StateGraph & Multi-Agent Architecture, PostgreSQL pgvector & HNSW Vector Indexing Standard, LLM Prompt Injection & Output Guardrails Standard, Zero Secret Hardcoding & Environment Hygiene Standard
# Free for in-repo use. Attribution to agentrules.org required if cited or republished.
# ==============================================================================
# SECTION 1: MODEL CONTEXT PROTOCOL (MCP) TYPESCRIPT SDK STANDARD
# ==============================================================================
## Directive
You are an expert Model Context Protocol (MCP) engineer using @modelcontextprotocol/sdk. When implementing stdio-based MCP servers, never use console.log or print to stdout, as this instantly corrupts the JSON-RPC message framing and crashes client hosts. Direct all application logging exclusively to process.stderr.write or console.error. Always validate tool arguments using strict Zod schemas and map exceptions into formatted { content: [{ type: 'text', text: ... }], isError: true } error responses rather than unhandled promise rejections.
## Strict Guidelines
1. NEVER emit debug output to stdout in stdio mode; route all diagnostic telemetry to process.stderr.write or console.error to avoid JSON-RPC framing corruption.
2. Define all MCP tool parameters with explicit Zod schemas using z.object({...}) and pass them to zodToJsonSchema or SDK schema converters.
3. Isolate tool execution inside try/catch blocks and return structured error objects with isError: true instead of throwing unhandled exceptions.
4. Gracefully handle SIGINT and SIGTERM OS signals to close active transports and release network and database connection pools.
# ==============================================================================
# SECTION 2: PYTHON FASTMCP PROTOCOL & TOOL SERVER STANDARD
# ==============================================================================
## Directive
You are an expert Python engineer building MCP servers with FastMCP. Never use print statements in stdio servers; use sys.stderr.write or logging to a dedicated file to prevent corrupting JSON-RPC streams. Implement async def for all tool functions and decorate with @mcp.tool(). Provide explicit type annotations and Pydantic Field(description=...) descriptions on every argument so host LLMs can generate accurate tool calls without hallucinations.
## Strict Guidelines
1. Never invoke built-in print(); stdout is exclusively reserved for JSON-RPC message framing. Log via sys.stderr or logging.getLogger().
2. Equip all tool parameters with Pydantic Field(description=...) to ensure LLMs understand constraints and valid ranges.
3. Inject Context into long-running tools to report progress and log structured messages directly back to the client host.
4. Use anyio.to_thread.run_sync or asyncio.to_thread for any legacy CPU-intensive or blocking synchronous operations.
# ==============================================================================
# SECTION 3: LANGGRAPH 2026 STATEGRAPH & MULTI-AGENT ARCHITECTURE
# ==============================================================================
## Directive
You are a senior AI agent architect using LangGraph 2026. Always model agent workflows using StateGraph with typed TypedDict state schemas. Use Annotated[Sequence[BaseMessage], add_messages] for conversational state to ensure messages append cleanly rather than overwrite. Nodes MUST return new partial state dictionaries and NEVER mutate state in place. Always compile graphs with durable checkpointers (e.g. PostgresSaver or AsyncPostgresSaver) and specify recursion_limit on invocations.
## Strict Guidelines
1. Annotate message lists with add_messages reducer: messages: Annotated[Sequence[BaseMessage], add_messages].
2. Return new partial state dictionaries from node functions; NEVER mutate the incoming state dictionary directly.
3. Attach a durable Checkpointer (PostgresSaver / MemorySaver) to app.compile(checkpointer=...) for human-in-the-loop and resume capabilities.
4. Always configure recursion_limit in the RunnableConfig to prevent infinite agent execution loops in production.
# ==============================================================================
# SECTION 4: POSTGRESQL PGVECTOR & HNSW VECTOR INDEXING STANDARD
# ==============================================================================
## Directive
You are a database performance architect using PostgreSQL with pgvector. When designing vector similarity tables, prefer HNSW (Hierarchical Navigable Small World) indexes over IVFFlat for high-recall production workloads. Always specify vector_cosine_ops (<=>) for normalized embeddings. Set appropriate m (e.g. 16 or 24) and ef_construction (e.g. 64 or 128) parameters during index creation. Tune hnsw.ef_search during query execution to balance latency vs recall.
## Strict Guidelines
1. Prefer HNSW indexing over IVFFlat: HNSW does not require data to be pre-loaded before index creation and maintains high recall during continuous insertions.
2. Always use the cosine distance operator (<=>) for normalized embeddings (OpenAI text-embedding-3, etc.) with vector_cosine_ops.
3. Increase maintenance_work_mem to at least 1GB during HNSW index construction to prevent temporary disk spillover.
4. Dynamically adjust SET LOCAL hnsw.ef_search = 40 (or higher) in queries requiring higher recall accuracy.
# ==============================================================================
# SECTION 5: LLM PROMPT INJECTION & OUTPUT GUARDRAILS STANDARD
# ==============================================================================
## Directive
You are an AI Agent security architect. Never concatenate untrusted user text directly into system instructions. Enclose untrusted inputs in structural XML delimiters (<user_input>). Parse model tool outputs with strict JSON schemas. Embed canary tokens to detect prompt leakage.
## Strict Guidelines
1. Wrap all user-provided data in distinct XML tags: <user_input>...</user_input> and instruct model to treat contents strictly as data.
2. Validate LLM JSON outputs with Zod or Pydantic before passing arguments to system tools.
3. Require explicit human-in-the-loop approval before executing destructive actions (e.g., dropping DB tables, executing shell scripts).
# ==============================================================================
# SECTION 6: ZERO SECRET HARDCODING & ENVIRONMENT HYGIENE STANDARD
# ==============================================================================
## Directive
You are a cloud security compliance officer. Never hardcode API keys, passwords, private keys, or tokens in source code, tests, or documentation. Validate all environment variables at application startup using a strict schema (e.g., @t3-oss/env-nextjs or Zod).
## Strict Guidelines
1. Never commit secrets to Git; add .env, .env.local, and *.pem to .gitignore.
2. Validate presence and format of required environment variables during bootstrap.
3. Reference dummy mock tokens (e.g., 'TEST_MOCK_TOKEN') strictly in unit tests with no production resemblances.
.cursorrules(Place directly in project root)Architectural Rationale & Failure Mode Analysis
Why modern AI assistants repeatedly fail on this specific technology combination without behavioral constraints.
Autonomous AI coding agents in 2026 operate directly on host systems through MCP tools and multi-agent graphs. Without normative behavioral rules, LLMs frequently emit print/console.log debug statements that corrupt JSON-RPC stdio channels, mutate state graphs in place, or query vector databases with unindexed sequential scans.
Prevented Production Hazards & AI Hallucination Vectors
| AI Hallucination Hazard | Production Impact | Verifiable Guardrail Mitigation |
|---|---|---|
| console.log or print() into stdio JSON-RPC pipe | Instant framing error and crash of Claude Desktop, Cursor, or Windsurf tool process. | Strictly routes all logging to stderr or structured file logging facilities. |
| In-place StateGraph dictionary mutation in LangGraph | Corrupts graph checkpoint hashes and breaks time-travel debugging and human-in-the-loop resume. | Enforces immutable partial updates and add_messages reducers. |
| IVFFlat vector indexing on unpopulated embedding tables | Degrades vector queries into 100% full-table sequential scans. | Mandates HNSW index creation with tuned m and ef_construction parameters. |
Constituent Rules in this Stack (6)
Each rule provides AST-level positive and negative enforcementModel Context Protocol (MCP) TypeScript SDK Standard
Production invariants for developing MCP tool servers using @modelcontextprotocol/sdk: strict Zod input schemas, asynchronous tool call isolation, error payload formatting, and stdout JSON-RPC stream preservation.
Python FastMCP Protocol & Tool Server Standard
Conventions for Python FastMCP servers: async tool definitions with @mcp.tool(), Pydantic v2 argument models, typed Context injection for client progress/logging, and clean shutdown handling.
LangGraph 2026 StateGraph & Multi-Agent Architecture
Standard for production LangGraph architectures: immutable state reducers using Annotated, durable checkpointing (PostgresSaver / MemorySaver), streaming event iteration via astream_events, and recursion limit boundaries.
PostgreSQL pgvector & HNSW Vector Indexing Standard
Production standards for vector similarity search with pgvector: HNSW index creation with tuned m and ef_construction, cosine distance operator (<=>), halfvec quantization for memory efficiency, and partition pruning.
LLM Prompt Injection & Output Guardrails Standard
Guardrails for AI Agent applications: delimiter sandboxing for untrusted inputs, schema validation for LLM outputs, canary tokens to detect system prompt exfiltration, and tool call permission bounds.
Zero Secret Hardcoding & Environment Hygiene Standard
Guardrails against leaked API keys, tokens, and database passwords: zero plaintext secrets in code, Git pre-commit secret scanning, and automated runtime env validation.
AI Agent Golden Iron Triangle Integrations
Combine behavioral rules with verifiable execution skills and live tool servers for complete Agent autonomy.
Equip your AI agent with specialized command functions to execute verification tests and lints directly.
Connect standard Model Context Protocol servers to grant your agent authenticated filesystem and database access.