
typed-service-contracts
Architecture standard for building robust, type-safe TypeScript services using the "Spec and Handler" pattern. Use when building CLIs, libraries, or complex business logic.
- Installs
- 95
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/google-labs-code/stitch-sdk --skill typed-service-contracts- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads typed-service-contracts automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Typed Service Contracts (Spec & Handler Pattern)
This skill defines a Vertical Slice Architecture backed by Design by Contract (DbC) principles. It treats application logic as rigorously defined Units of Work where inputs are parsed (not just validated) and errors are treated as values (Result Pattern) rather than exceptions.
When to use this skill
- Building CLIs or Libraries: When you need strict boundaries between user input and system logic.
- Complex Validation: When inputs require transformation (parsing) before being useful (e.g., ensuring a string is a valid file path).
- High-Reliability Requirements: When you cannot afford unhandled runtime exceptions and need exhaustive error handling.
- Testing Focus: When you want to separate data validation tests from business logic tests.
Architecture Components
1. The Spec (spec.ts)
The "Contract" or "Port". It defines the What. It must contain:
- Input Schema: A Zod schema that parses raw input into a valid DTO.
- Output Schema: A Zod schema defining the successful data structure.
- Error Schema: A discriminated union of specific failure modes (not generic errors).
- Result Type: A
DiscriminatedUnionofSuccess | Failure. - Interface: The capability definition (e.g.,
interface ConfigureSpec).
2. The Handler (handler.ts)
The "Implementation" or "Adapter". It defines the How. It must:
- Implement the Interface defined in the Spec.
- Be an "Impure" class that handles side effects (File System, API calls).
- NEVER throw exceptions. It must catch internal errors and map them to the
Resulttype.
How to use it
Step 1: Define the Contract (spec.ts)
Follow this template to define the boundaries.
import { z } from "zod";
// 1. VALIDATION HELPERS (Reusable Refinements)
export const SafePathSchema = z
.string()
.min(1)
.refine((p) => !p.includes(".."), "No traversal allowed");
// 2. INPUT (The Command) - "Parse, don't validate"
export const MyTaskInputSchema = z.object({
path: SafePathSchema,
force: z.boolean().default(false),
});
export type MyTaskInput = z.infer<typeof MyTaskInputSchema>;
// 3. ERROR CODES (Exhaustive)
export const MyTaskErrorCode = z.enum([
"FILE_NOT_FOUND",
"PERMISSION_DENIED",
"UNKNOWN_ERROR",
]);
// 4. RESULT (The Monad)
export const MyTaskSuccess = z.object({
success: z.literal(true),
data: z.string(), // The output payload
});
export const MyTaskFailure = z.object({
success: z.literal(false),
error: z.object({
code: MyTaskErrorCode,
message: z.string(),
suggestion: z.string().optional(),
recoverable: z.boolean(),
}),
});
export type MyTaskResult =
| z.infer<typeof MyTaskSuccess>
| z.infer<typeof MyTaskFailure>;
// 5. INTERFACE (The Capability)
export interface MyTaskSpec {
execute(input: MyTaskInput): Promise<MyTaskResult>;
}
Step 2: Implement the Handler (handler.ts)
Follow this template to implement the logic.
import { MyTaskSpec, MyTaskInput, MyTaskResult } from "./spec.js";
import * as fs from "fs";
export class MyTaskHandler implements MyTaskSpec {
async execute(input: MyTaskInput): Promise<MyTaskResult> {
try {
// 1. Business Logic
if (!fs.existsSync(input.path)) {
// 2. Explicit Error Return (No Throwing)
return {
success: false,
error: {
code: "FILE_NOT_FOUND",
message: `Path does not exist: ${input.path}`,
recoverable: true,
},
};
}
// 3. Success Return
return {
success: true,
data: "Operation complete",
};
} catch (error) {
// 4. Safety Net: Catch unknown runtime errors
return {
success: false,
error: {
code: "UNKNOWN_ERROR",
message: error instanceof Error ? error.message : String(error),
recoverable: false,
},
};
}
}
}
Step 3: Testing Strategy
Do not write monolithic tests. Split them into Contract Tests and Logic Tests.
A. Contract Tests (Schema)
Test the Bouncer. Ensure invalid data is rejected before it reaches the handler.
- Focus: Edge cases, validation rules, Zod refinements.
- Style: Data-driven (Table tests).
// spec.test.ts
import { MyTaskInputSchema } from "./spec";
const invalidCases = [
{ val: "../etc/passwd", err: "No traversal allowed" },
{ val: "", err: "min(1)" },
];
test.each(invalidCases)("validates paths", ({ val, err }) => {
const result = MyTaskInputSchema.safeParse({ path: val });
expect(result.success).toBe(false);
});
B. Logic Tests (Handler)
Test the Chef. Mock external dependencies (fs, network) and assert the Result Object.
- Focus: Business logic flow, error mapping, success states.
- Style: Mocked unit tests or Scenario Runners.
// handler.test.ts
import { MyTaskHandler } from "./handler";
import { vi } from "vitest"; // or jest
test("returns FILE_NOT_FOUND if path missing", async () => {
// MOCK
vi.mocked(fs.existsSync).mockReturnValue(false);
// EXECUTE
const handler = new MyTaskHandler();
const result = await handler.execute({ path: "/fake" });
// ASSERT (Check the Result Object)
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.code).toBe("FILE_NOT_FOUND");
}
});
FAQ
What does the typed-service-contracts skill do?
Architecture standard for building robust, type-safe TypeScript services using the "Spec and Handler" pattern. Use when building CLIs, libraries, or complex business logic.
How do I install typed-service-contracts?
Run npx skills add https://github.com/google-labs-code/stitch-sdk --skill typed-service-contracts in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/typed-service-contracts/ (personal) or .claude/skills/typed-service-contracts/ (project).
Which AI agents can use typed-service-contracts?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is typed-service-contracts safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains typed-service-contracts?
It is published by google-labs-code in google-labs-code/stitch-sdk, and it is an official skill from the maker of the technology it covers. It has 95 recorded installs.
More from google-labs-code/stitch-sdk
stitch-sdk-usage
google-labs-code/stitch-sdk
Use the Stitch SDK to generate, edit, and iterate on UI screens from text prompts, manage projects, and retrieve screen HTML/images. Use when the user wants to consume the SDK in their application.
stitch-sdk-readme
google-labs-code/stitch-sdk
Open the skill to read its SKILL.md instructions.
stitch-sdk-development
google-labs-code/stitch-sdk
Open the skill to read its SKILL.md instructions.
stitch-sdk-domain-design
google-labs-code/stitch-sdk
Open the skill to read its SKILL.md instructions.
tdd-red-green-refactor
google-labs-code/stitch-sdk
Open the skill to read its SKILL.md instructions.
stitch-sdk-pipeline
google-labs-code/stitch-sdk
Open the skill to read its SKILL.md instructions.
Popular code quality & workflow skills
grill-me
mattpocock/skills
A relentless interview to sharpen a plan or design.
improve-codebase-architecture
mattpocock/skills
Scan a codebase for deepening opportunities, present them as a visual HTML report, then grill through whichever one you pick.
handoff
mattpocock/skills
Compact the current conversation into a handoff document for another agent to pick up.
domain-modeling
mattpocock/skills
Build and sharpen a project's domain model. Use when discussing codebase terminology, writing or editing a GLOSSARY.md, or recording or editing an ADR.
codebase-design
mattpocock/skills
Shared vocabulary for designing deep modules. Use when the user wants to design or improve a module's interface, find deepening opportunities, decide where a seam goes, make code more testable or AI-navigable, or when another skill needs the deep-module vocabulary.
diagnosing-bugs
mattpocock/skills
Diagnosis loop for hard bugs and performance regressions. Use when the user says "diagnose"/"debug this", or reports something broken/throwing/failing/slow.