Skip to main content
CRUCIBLE
Legacy Reference Archive: This 44-chapter book reference has been distilled into Academy A01 (8 Executable Modules) with Tier-Adaptive Productive Failure, Kore/Puck voice, and live Firecracker labs.
Open Academy A01 →
COURSE 0 · SERVER BUILDING & LIFECYCLE MASTERY

Zero-to-Production Linux, Containers, Networking & Recovery

PROGRESS: 0 / 72 (0%)0/44L · 0Q · 0VM
CH 09 · PART III · AI, MCP, INFERENCE & PLATFORMS (CH 09–13) · 1,105 WORDS (6 MIN)

9 AI applications agents and MCP

A model API is an external dependency with latency, rate limits, cost, evolving behavior, and possible failures. Your application owns validation, authorization, persistence, user-facing contracts, and recovery. A model does not replace those responsibilities.

FULL WAR-ROOM →
INTERACTIVE AI & GPU BOUNDARY · CLICK ANY STAGE TO INSPECT

Production AI Stack: Gateway Budget -> Hybrid RAG ACL -> MCP Guard -> GPU KV-Cache

How production teams bound token spend, block cross-tenant retrieval leaks, and prevent CUDA OOM.

fetchescallsservesLLM GatewayTimeouts · Token CapsPre-Filtered RAGWHERE tenant_id = ?MCP Tool GuardAllowlist · SSRF BlockGPU KV-CacheTTFT · Admission Cap
SELECTED LAYER · LLM GATEWAY
Enforces per-tenant rate limits, strict request timeouts, and JSON schema validation around model calls.
Common failure: Unbounded LLM calls hanging API workers or running up runaway token invoices during retry storms.
$ curl -s http://127.0.0.1:8000/health

Outcome: add AI capabilities without giving a model uncontrolled authority. Prerequisites: backend, security, and durable-work chapters. Environment: the local read-only MCP adapter is runnable; paid model integrations and remote OAuth deployment are extension exercises.

Add a model behind a service boundary

A model API is an external dependency with latency, rate limits, cost, evolving behavior, and possible failures. Your application owns validation, authorization, persistence, user-facing contracts, and recovery. A model does not replace those responsibilities.

For the automation service, an AI extension might summarize submitted text. Define an output schema, maximum input length, maximum output tokens, deadline, and cost budget. Store provider/model/version metadata with the result. Keep provider credentials only in the worker that needs them. Do not make a private key a tool argument or embed it in a prompt.

The deterministic analyzer remains the default so local tests need no paid service. Add a provider adapter behind a small interface, test its success and failure responses with fixtures, and run separately marked live tests with a fixed budget. A mocked response proves handling, not model quality or provider compatibility.

Structured output and evaluation

A valid JSON object is not necessarily a correct answer. Validate its schema and evaluate its meaning against representative examples. Build a dataset containing normal requests, ambiguous inputs, adversarial instructions, sensitive-data cases, long inputs, and expected refusals or escalations. Separate development examples from held-out evaluation examples.

Use deterministic checks for properties such as required fields, permitted categories, numeric ranges, and forbidden actions. Use human review or carefully calibrated model judging for semantic quality. A model judge can be biased or inconsistent; record its prompt/version and compare it with human labels. Track false positives and false negatives rather than a single unexplained score.

Version prompts and datasets with the code. Before upgrading a model, compare quality, latency, cost, and safety behavior under the same workload. A provider alias may change behavior without a code change; choose a versioning strategy appropriate to the contract.

Retrieval and private data

Retrieval-augmented generation adds selected source material to a model request. Its pipeline includes ingestion, parsing, chunking, indexing, retrieval, permission filtering, generation, and citation. Each step can fail independently. A good answer to the wrong tenant's document is a security incident.

Apply access controls before retrieval results enter the model context. Track document versions and deletions so removed content is not silently retained in an index. Evaluate retrieval quality separately from answer quality. Start with lexical search and a small corpus baseline before assuming embeddings or reranking solve the problem.

Treat retrieved content as untrusted data. It may contain instructions attempting to override the workflow. Prompt wording helps communicate boundaries, but application controls must enforce which tools, destinations, and actions are possible.

Agents as state machines

An agent chooses operations based on state and model output. Keep state explicit: input, authenticated principal, allowed actions, previous results, pending approval, retry count, and budget. Bound steps, wall-clock duration, model tokens, tool execution time, and money independently.

Persist checkpoints for long-running workflows. A human approval should bind to the exact operation, resource, parameters, identity, and expiry; “the user said yes earlier” is not a universal permission. Revalidate permissions when resuming. Record approvals and outcomes without exposing secrets.

Use a workflow framework when its durable execution and observability solve a demonstrated need. Learn its replay semantics, versioning, cancellation, and activity idempotency. Framework selection does not eliminate distributed systems problems.

What MCP provides

MCP standardizes how a client discovers and invokes tools and accesses other protocol capabilities. It does not automatically provide correct business permissions, safe tool behavior, trustworthy descriptions, or durable side effects. Read the versioned specification your client/server combination implements.

Local stdio starts a server process and communicates over its input/output. Reserve stdout for protocol traffic; put diagnostics on stderr. Remote HTTP introduces networking, TLS, authentication, authorization, session, proxy, and compatibility decisions. Streamable HTTP is a transport; it is not an authorization policy.

The [MCP authorization specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) describes the HTTP authorization model and its requirements. Protected remote services need a deliberate interoperable implementation. The local example does not become a secure multi-user remote service by changing a transport flag.

Run the included adapter

Start the Chapter 3 API and create a job. From the same example directory, load your lab environment and launch:

bash
set -a
. ./.env
set +a
export JOB_API_URL=http://127.0.0.1:8000
uv run python mcp_adapter.py

The server waits for a stdio-speaking client; a silent terminal is expected. Configure your MCP client to launch that command with the example directory as its working directory and the required environment. Use absolute executable paths if the client's PATH differs from your terminal. For the container API, set the URL to http://127.0.0.1:18768.

The adapter exposes only get_job. Its input is a UUID, destination is operator-configured, and token is fixed to one tenant. It has a request timeout and does not follow redirects. The returned object contains job status and result. Unknown jobs and service failures become tool errors. The in-process protocol test exercises discovery and invocation; see [FastMCP client documentation](https://gofastmcp.com/clients/client).

Tool design contract

For every tool specify name, purpose, strict input fields, output shape, permissions, side effects, idempotency, limits, and failure modes. “Read-only” annotations help a client understand intent; server-side enforcement remains necessary. Avoid an arbitrary SQL tool, arbitrary shell tool, or arbitrary URL fetcher as your first agent integration.

A write tool should expose a narrow business operation. Separate preview from execution where consequences warrant it. Return an operation ID so the application can reconcile ambiguous outcomes. Do not tell an agent that an upstream timeout means nothing happened; the upstream may have committed before the response was lost.

Remote MCP exercise

Build a separate protected HTTP deployment using the selected SDK's supported authorization integration. Configure TLS, resource/audience validation, token scope checks, origin handling, rate limits, session behavior, and allowed clients. Test discovery and authorization with at least two intended clients and the exact protocol version.

Add negative tests for missing token, wrong audience, expired token, insufficient scope, cross-tenant object access, and malicious tool arguments. Verify that proxy and load-balancer settings preserve the expected transport behavior. Document whether state is local, shared, or stateless and how reconnects work. This is an advanced exercise, not a feature silently supplied by the local adapter.

Exit exercise

Have an MCP client discover the tool, retrieve an owned job, and fail to retrieve another tenant's job. Design a summarization extension with a fixed budget and evaluation set. Explain where prompt injection could enter and which application controls prevent it from changing destination, identity, permissions, or spending limits.

ACTIVE-RECALL MASTERY CHECKPOINT · CH 09

Lock in what you just learned (3 quick questions)

PASS 2/3 FOR +30 XP
Q1.Why place LLM calls behind a dedicated service boundary with strict timeouts, schema validation, and budget caps?
Q2.In a multi-tenant RAG pipeline, when MUST tenant access-control (ACL) filtering be applied?
Q3.Why design AI agents and MCP tool servers as bounded state machines with strict host/tool allowlists?
Answered 0 / 3