The Complete Production SOP: How to Deploy and Run tRPC Server Procedures, Routers & Middleware Context in Autonomous AI Agents
Step-by-step SOP to install and run tRPC Server Procedures, Routers & Middleware Context in Codex, Claude Code, & Cursor. Includes verified prompts and fixes.
Technical Overview & Architectural Context
Autonomous coding agents frequently stumble when generating modern tRPC (v10/v11) server backends. Without deterministic boundaries, LLMs conflate legacy v9 syntax with modern builder patterns, omit contextual type inference in `initTRPC.context<Context>().create()`, leak private session data by chaining unverified context mutations, and fail to isolate shared middlewares. When constructing API layers, agents often hallucinate schema generation steps or redundantly serialize input schemas rather than relying on pure TypeScript inference. The `trpc-server-type-safe-procedures` skill establishes strict procedural parameters for autonomous agents operating across Codex, Claude Code, Cursor, and Windsurf. By enforcing a single initialization anchor (`trpc.ts`), deterministic middleware context propagation, and explicit `publicProcedure` vs `protectedProcedure` delineation via Zod inputs, this skill ensures agents deliver compile-ready, zero-bloat RPC pipelines that immediately pass strict TypeScript audits without human intervention.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into agent runtime path.
Agent runtimes such as Claude Code, Codex, and Cursor read custom skills from designated system or workspace directories. Injecting `SKILL.md` into `~/.agents/skills/trpc-server-type-safe-procedures` enables runtime hot-reloading. The agent scans the frontmatter triggers (`create trpc router`, `protectedprocedure trpc middleware`, `input validation trpc zod`) and applies the deterministic initialization constraints whenever fullstack router tasks are requested.
mkdir -p ~/.agents/skills/trpc-server-type-safe-procedures && cat << 'EOF' > ~/.agents/skills/trpc-server-type-safe-procedures/SKILL.md
---
name: "trpc-server-type-safe-procedures"
description: "Build 100% end-to-end type-safe APIs without schemas, code generation, or runtime bloat."
metadata:
author: "tRPC"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "create trpc router"
- "protectedprocedure trpc middleware"
- "input validation trpc zod"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# tRPC Server Procedures, Routers & Middleware Context
Architects tRPC v10/v11 server routers: initTRPC.context<Context>().create(), publicProcedure vs protectedProcedure, Zod input validation (.input(schema)), output schema inference, and error formatting.
EOFimport { initTRPC, TRPCError } from '@trpc/server';
import type { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch';
import { z } from 'zod';
export interface Context {
user: { id: string; role: 'admin' | 'user' } | null;
reqHeaders: Headers;
}
export const createContext = async (opts: FetchCreateContextFnOptions): Promise<Context> => {
const authHeader = opts.req.headers.get('authorization');
const user = authHeader ? { id: 'usr_123', role: 'user' as const } : null;
return { user, reqHeaders: opts.req.headers };
};
const t = initTRPC.context<Context>().create({
errorFormatter({ shape, error }) {
return {
...shape,
data: {
...shape.data,
zodError: error.cause instanceof z.ZodError ? error.cause.flatten() : null,
},
};
},
});
export const router = t.router;
export const publicProcedure = t.procedure;
const isAuthed = t.middleware(async ({ ctx, next }) => {
if (!ctx.user) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Authentication required' });
}
return next({
ctx: {
user: ctx.user,
},
});
});
export const protectedProcedure = t.procedure.use(isAuthed);Keep the tRPC instance initialization in an isolated module (`trpc.ts`). Instruct the agent to import `publicProcedure` and `protectedProcedure` rather than re-invoking `initTRPC.create()`, saving ~450 tokens per file.
Never allow the agent to instantiate `initTRPC.create()` in multiple files. Multiple instances break router composition and destroy root context type inference.
Environment Secrets & Dependency Validation
Install core peer packages and configure tsconfig compiler options for clean inference.
tRPC requires `@trpc/server` and a validation engine like `zod`. Furthermore, TypeScript strict mode must be activated in `tsconfig.json` so that procedure outputs and contextual middlewares can correctly narrow types without implicit `any` fallbacks.
pnpm add @trpc/server zod && pnpm add -D typescript @types/node{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"declaration": true,
"skipLibCheck": true,
"isolatedModules": true
}
}Ensure `declaration: true` is set in tsconfig if the `AppRouter` type is exported across an npm/pnpm workspace monorepo package boundary.
Omitting `"strict": true` disables Zod runtime-to-compile-time schema inference, allowing agents to pass unvalidated types silently into database clients.
Intent Matching & Trigger Invocation
Trigger deterministic procedure generation using explicit skill trigger phrases.
Agents loaded with `trpc-server-type-safe-procedures` watch for trigger phrases in developer instructions. When formulating prompts, include triggers like 'create trpc router' and 'protectedprocedure trpc middleware' to force the LLM to pull execution boundaries directly from the SKILL.md definition rather than relying on stale generic web training data.
import { z } from 'zod';
import { router, publicProcedure, protectedProcedure } from '../trpc';
export const postRouter = router({
list: publicProcedure
.input(z.object({ limit: z.number().min(1).max(100).default(10) }))
.query(async ({ input, ctx }) => {
return { items: [], limit: input.limit };
}),
create: protectedProcedure
.input(z.object({ title: z.string().min(5), content: z.string() }))
.mutation(async ({ input, ctx }) => {
// ctx.user is non-nullable here due to isAuthed middleware
return {
id: 'post_new',
title: input.title,
authorId: ctx.user.id,
};
}),
});Use concise verbs matching the frontmatter triggers, such as: 'Execute protectedprocedure trpc middleware to enforce admin role checks'.
Avoid vague instructions like 'make an API endpoint'. Vague prompts make the agent default to standard Express/Next.js route handlers rather than invoking the tRPC procedure pipeline.
Verification, Linting & Output Quality Gate
Execute automated typecheck and self-healing loops to verify end-to-end type safety.
The skill enforces that the agent runs compiler verification before marking tasks complete. It creates the root `AppRouter`, exports its type definition, and invokes `tsc --noEmit` to verify type resolution and middleware context narrowing.
pnpm tsc --noEmit && pnpm eslint src/server --ext .tsimport { router } from './trpc';
import { postRouter } from './routers/post';
export const appRouter = router({
post: postRouter,
});
export type AppRouter = typeof appRouter;Review `git diff --stat` to verify that the agent only modified procedure files within `src/server` and did not modify package lockfiles or tsconfig unnecessarily.
Never allow the agent to export `appRouter` as default without exporting `export type AppRouter`. Frontend consumer packages cannot infer client types without the exported type definition.
Real-World Scenario: Implement Type-Safe Organization Membership Router with Protected Middleware
“Using the trpc-server-type-safe-procedures skill, create trpc router for managing organization members. Implement a protectedprocedure trpc middleware checking if the user has role 'admin', and an input validation trpc zod procedure to invite members by email with role enum ('admin' | 'member'). Export the combined AppRouter type.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent bypassed `t.middleware()` or failed to return `next({ ctx: { user } })`, causing TypeScript to lose context narrowing from base Context to authenticated Context.
Ensure your middleware returns `next({ ctx: { user: ctx.user } })` where user is explicitly asserted or checked against null:
const isAuthed = t.middleware(async ({ ctx, next }) => {
if (!ctx.user) throw new TRPCError({ code: 'UNAUTHORIZED' });
return next({ ctx: { user: ctx.user } });
});Root Cause: TypeScript declaration generation (`declaration: true`) fails when the `Context` type is not exported from the module where `initTRPC.context<Context>()` is initialized.
Open `src/server/trpc.ts` and ensure `export type Context = ...` is explicitly exported so consuming packages can emit declaration maps.Frequently Asked Questions (tRPC Server Procedures, Routers & Middleware Context SOP)
Q:Can I use tRPC Server Procedures, Routers & Middleware Context across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the universal SKILL.md specification. By mounting the file in your global or repository-level skills path (`~/.agents/skills/trpc-server-type-safe-procedures/SKILL.md` or `.cursor/skills/`), any runtime that adheres to procedural AI manifests can parse the triggers and apply the SOP.
Q:How does tRPC Server Procedures, Routers & Middleware Context prevent context window overflow during long agent sessions?
Instead of pasting entire multi-file API examples into user prompts, the skill defines strict modular boundaries: initialize once in `trpc.ts`, export reusable procedures (`publicProcedure`, `protectedProcedure`), and chain modular sub-routers. This minimizes repetitive tokens and prevents the agent from re-architecting boilerplate on every turn.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100. It requires read access to inspect workspace files and write access restricted strictly to workspace code directories. Shell execution and outbound network access are disabled during procedure authoring.
Ready to equip your autonomous agent with tRPC Server Procedures, Routers & Middleware Context?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.