backend Stack6 Harmonized RulesMulti-Platform Compatible

OpenAI Structured Outputs + vLLM + LangChain LCEL + OWASP Guardrails

Enterprise generative AI serving architecture. Enforces CFG grammar-constrained JSON generation with zodResponseFormat, vLLM continuous batching with PagedAttention, async streaming LCEL chains, and indirect prompt injection boundaries.

CLI One-Linernpx agentrules
npx agentrules init

Auto-detects this stack and writes verified client instructions into your project root.

82 lines • ~2083 tokens
# Combined .cursorrules generated by AgentRules.org (https://agentrules.org)
# Specification Version: 2026.10-Industrial | Licensed under CC BY 4.0
# Stack: OpenAI Structured Outputs & Zod Strict JSON Schema Enforcement, vLLM Production Inference Serving & PagedAttention Optimization, LangChain Expression Language (LCEL) & Runnable Pipeline Standard, OWASP Top 10 for LLMs & Indirect Prompt Injection Defense, PostgreSQL pgvector & HNSW Vector Indexing Standard, Model Context Protocol (MCP) TypeScript SDK Standard
# Free for in-repo use. Attribution to agentrules.org required if cited or republished.

# ==============================================================================
# SECTION 1: OPENAI STRUCTURED OUTPUTS & ZOD STRICT JSON SCHEMA ENFORCEMENT
# ==============================================================================
## Directive
You are an AI infrastructure and LLM systems engineer. When requesting structured JSON from OpenAI models (gpt-4o, gpt-4o-mini, o1), NEVER prompt with natural language 'Please output JSON' and parse raw text. Always use response_format: zodResponseFormat() with strict: true in TypeScript or parse with Pydantic in Python.

## Strict Guidelines
1. Always use openai.beta.chat.completions.parse() with zodResponseFormat(Schema, 'name') for guaranteed schema adherence.
2. Ensure all Zod schema fields are explicitly marked or nullable; strict mode rejects optional fields without explicit defaults or nullability.
3. Check completion.choices[0].message.refusal to gracefully handle safety refusals before accessing parsed fields.
4. Never perform manual regex stripping of '```json' or JSON.parse on unstructured message.content.


# ==============================================================================
# SECTION 2: VLLM PRODUCTION INFERENCE SERVING & PAGEDATTENTION OPTIMIZATION
# ==============================================================================
## Directive
You are a GPU infrastructure and LLM serving engineer. In production model serving, NEVER use vanilla HuggingFace pipeline() or AutoModelForCausalLM in web servers. Use vLLM AsyncLLMEngine with continuous batching, set gpu_memory_utilization accurately (0.90), enable enable_prefix_caching=True, and match tensor_parallel_size to physical GPU count.

## Strict Guidelines
1. Use AsyncLLMEngine for asynchronous HTTP/gRPC server integrations; do not use the synchronous LLM offline runner in web processes.
2. Set gpu_memory_utilization explicitly (typically 0.85-0.92) and configure max_model_len to prevent out-of-memory (OOM) allocation crashes.
3. Enable enable_prefix_caching=True to reuse KV caches across shared system prompts and multi-turn conversations.
4. Configure tensor_parallel_size equal to the number of available GPUs connected via NVLink; ensure Ray or PyTorch distributed backend is configured.


# ==============================================================================
# SECTION 3: LANGCHAIN EXPRESSION LANGUAGE (LCEL) & RUNNABLE PIPELINE STANDARD
# ==============================================================================
## Directive
You are a LangChain platform architect. Never import or use deprecated LangChain v0.1 classes such as LLMChain, initialize_agent, or AgentExecutor. Always construct pipelines using LangChain Expression Language (LCEL) with the pipe operator (|), RunnablePassthrough, and custom tool binding via model.bind_tools().

## Strict Guidelines
1. Compose prompt templates, models, and parsers using the LCEL pipe operator (|) rather than LLMChain.
2. Implement tool-calling agents using create_tool_calling_agent and modern AgentExecutor from langchain.agents, or prefer LangGraph StateGraph.
3. Always implement async streaming with chain.astream() or chain.astream_events() to enable real-time UI token streaming.
4. Pass callbacks or LangSmith metadata tags in the config dictionary ({'configurable': {...}, 'tags': [...]}) for end-to-end tracing.


# ==============================================================================
# SECTION 4: OWASP TOP 10 FOR LLMS & INDIRECT PROMPT INJECTION DEFENSE
# ==============================================================================
## Directive
You are an AI application security and adversarial defense architect. When building LLM-powered applications or autonomous agents, NEVER concatenate untrusted external inputs (emails, web pages, user queries) directly into the system instruction block. Always enclose untrusted data in structural XML tags (<user_input>...</user_input>), validate tool parameters with strict runtime schemas, and require human authorization for destructive actions.

## Strict Guidelines
1. Isolate untrusted data using explicit boundary delimiters (e.g. <untrusted_data>...</untrusted_data>) and instruct the model never to follow instructions inside the payload.
2. Screen user prompts and retrieved context using input guardrail classifiers (e.g. Llama Guard, NeMo Guardrails) before calling core LLMs.
3. Enforce human-in-the-loop confirmation gates (approval workflows) before executing irreversible actions (financial transfers, email sending, data deletion).
4. Filter model outputs using regex and semantic masks to prevent inadvertent disclosure of system prompts, API keys, or PII.


# ==============================================================================
# SECTION 5: 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 6: 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.
Target File:.cursorrules
AgentRules.org RFC-2119 Matrix Standard

Architectural Rationale & Failure Mode Analysis

Why modern AI assistants repeatedly fail on this specific technology combination without behavioral constraints.

Autonomous agent and RAG systems collapse when models output non-deterministic markdown fences, un-batched inference servers stall under concurrent load, or untrusted emails hijack agent tool calls. This stack erects complete infrastructure guardrails.

Prevented Production Hazards & AI Hallucination Vectors

AI Hallucination HazardProduction ImpactVerifiable Guardrail Mitigation
Regex stripping of ```json code fences crashing on omitted fieldsProduction agent pipeline crashes and broken frontend state.Native OpenAI response_format: zodResponseFormat with strict: true.
Single-thread HuggingFace pipeline blocking concurrent GPU requestsHigh request latency and out-of-memory GPU crashes.vLLM AsyncLLMEngine with continuous batching and PagedAttention prefix caching.
Indirect prompt injection in retrieved emails hijacking tool actionsData exfiltration and unauthorized execution of destructive commands.XML structural tagging boundaries and human-in-the-loop authorization gates.

Constituent Rules in this Stack (6)

Each rule provides AST-level positive and negative enforcement
backendcritical

OpenAI Structured Outputs & Zod Strict JSON Schema Enforcement

Production standard for deterministic LLM tool calling and structured outputs. Mandates native response_format: zodResponseFormat with strict: true, eliminates flaky regex markdown code-block parsing, and guarantees 100% schema compliance.

#openai#structured-outputs#zod
View Spec
backendcritical

vLLM Production Inference Serving & PagedAttention Optimization

Production deployment standard for open-weights LLMs (Llama 3, Mistral, Qwen 2.5) using vLLM. Enforces PagedAttention VRAM management, continuous request batching, prefix caching, and tensor-parallel scaling to maximize token throughput.

#vllm#llm-serving#paged-attention
View Spec
backendcritical

LangChain Expression Language (LCEL) & Runnable Pipeline Standard

Production standard for LangChain applications using LangChain Expression Language (LCEL). Deprecates legacy AgentExecutor, LLMChain, and initialize_agent in favor of composable Runnable sequences with native streaming, async batching, and LangSmith tracing.

#langchain#lcel#runnable
View Spec
securitycritical

OWASP Top 10 for LLMs & Indirect Prompt Injection Defense

Enterprise security standard mitigating OWASP Top 10 for Large Language Model Applications (LLM01 Prompt Injection, LLM02 Sensitive Information Disclosure, LLM08 Excessive Agency). Mandates dual-boundary structural tagging, input guardrail scanning, and human-in-the-loop gates for high-impact actions.

#owasp#llm-security#prompt-injection
View Spec
backendhigh

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.

#pgvector#postgresql#hnsw
View Spec
backendcritical

Model 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.

#mcp#ai-agent#typescript
View Spec

AI Agent Golden Iron Triangle Integrations

Combine behavioral rules with verifiable execution skills and live tool servers for complete Agent autonomy.

Recommended Agent Skillsaskills.dev

Equip your AI agent with specialized command functions to execute verification tests and lints directly.

Recommended MCP Tool Serversmcp-serverlist.com

Connect standard Model Context Protocol servers to grant your agent authenticated filesystem and database access.