# Standardizing LLM Agent Skills with Stitch: Build Portable, Reusable AI Capabilities

> Learn how to use the open‑source Stitch Skills library to design portable LLM agent capabilities, integrate them into React, Next.js, Node.js, and Ruby on

I’ve been building AI‑augmented services for a decade, and the one thing that still trips me up is the sheer variety of ways people ship “LLM agent skills.” One team will write a Python function, another will drop a JavaScript file into a Lambda, a third will spin up a Rust binary and call it over gRPC. The result is a Frankenstein ecosystem where every skill has its own build pipeline, its own deployment model, and its own runtime quirks. When I finally needed to reuse a code‑review skill across three different products—one in Next.js, one in a Go microservice, and one in a legacy Rails app—I spent more time wiring adapters than actually writing business logic.

That experience pushed me toward a more disciplined approach: **Stitch**. Stitch is a thin, language‑agnostic wrapper that lets you describe an LLM agent capability once—what I call a *Stitch Skill*—and then plug it into any stack that can speak HTTP or a simple binary protocol. In this post I’ll walk through the mental model, the concrete file layout, and the trade‑offs I’ve observed in production. I’ll also be blunt about the things I’m still unsure of, because the field moves faster than any spec can keep up.

---

## Why we need a lingua franca for LLM agent capabilities

LLM agents are essentially *functions* that accept a prompt (or a structured request) and return a response. In practice, however, they have grown into mini‑services with:

* **Stateful context** (e.g., a conversation ID, a vector store handle)
* **Side‑effects** (e.g., writing to a database, invoking a CI pipeline)
* **Non‑deterministic latency** (model inference time, external API calls)

When each team rolls its own wrapper, the following problems surface:

| Symptom | Typical cause |
|---|---|
| Skill A works in dev but crashes in prod | Different environment variables, missing runtime dependencies |
| Two services expose the same “summarize” capability but have incompatible JSON payloads | No shared contract |
| Updating the underlying LLM model breaks downstream callers | No versioning or deprecation path |

I’ve seen teams spend weeks debugging a “missing field” error that boiled down to a mismatched camelCase vs. snake_case key in a Python dict. The pain isn’t just developer friction; it’s also a security risk when input validation is duplicated across languages.

A **standardized skill interface** solves three things:

1. **Portability** – Write the core logic once, run it anywhere.
2. **Reusability** – Share the same skill across micro‑frontends, back‑ends, and even CLI tools.
3. **Governance** – Enforce versioning, deprecation, and quality gates centrally.

That’s the problem Stitch tries to solve.

---

## The design philosophy behind Stitch

Stitch deliberately stays out of the way of the LLM itself. It does **not** prescribe a model provider, a prompt template, or a token‑budgeting strategy. Instead, it defines a *skill contract* that any implementation must honor:

1. **Manifest‑first** – Every skill ships a `stitch.json` that declares its name, version, input schema, output schema, and required runtime adapters.
2. **Adapter‑based execution** – The core runtime is a tiny Node.js shim (`stitch-runtime`) that loads a language‑specific adapter (e.g., `stitch-adapter-python`, `stitch-adapter-rust`). The adapter is responsible for invoking the user‑provided handler and translating the result back to the manifest’s JSON schema.
3. **Semantic versioning** – Skills follow the same MAJOR.MINOR.PATCH rules as npm packages. A breaking change must bump the major version, which forces downstream callers to update their integration code.

Because the contract is JSON‑Schema‑based, any language that can read/write JSON can implement a Stitch Skill. The only *required* runtime dependency is a small HTTP server (or a Unix socket listener) that the adapter can talk to. This keeps the footprint low enough to run inside a Lambda, a Docker container, or even a Bash script.

> **Verification note**  
> The exact list of officially supported adapters (Node, Python, Rust, Bash) is based on the current open‑source repository as of the writing date. I have not verified support for other languages such as Java or Go; contributions are welcome.

---

## Core primitives: Skill Manifest, Input/Output contracts

A Stitch Skill lives in its own directory, typically under a monorepo `skills/` folder. The minimal layout looks like this:

```text
skills/
└─ summarize-article/
   ├─ stitch.json
   ├─ src/
   │  └─ handler.ts
   ├─ package.json          # only for Node adapters
   └─ README.md
```

### `stitch.json`

```json
{
  "$schema": "https://stitch.dev/schemas/skill-manifest.json",
  "name": "summarize-article",
  "version": "1.2.0",
  "description": "Generate a concise summary of a markdown article.",
  "runtime": {
    "adapter": "node",
    "entrypoint": "dist/handler.js"
  },
  "input": {
    "$ref": "./schemas/input.json"
  },
  "output": {
    "$ref": "./schemas/output.json"
  },
  "metadata": {
    "author": "jane.doe@fullstackweb.dev",
    "tags": ["nlp", "summarization"]
  }
}
```

* `runtime.adapter` tells the Stitch orchestrator which adapter to spin up. The `entrypoint` is the compiled artifact that the adapter will require.
* `input` and `output` are JSON‑Schema references. By keeping the schema in separate files you can version them independently and reuse them across skills.

### Input schema (`schemas/input.json`)

```json
{
  "$id": "summarize-article-input",
  "type": "object",
  "properties": {
    "markdown": {
      "type": "string",
      "description": "Full markdown source of the article."
    },
    "maxTokens": {
      "type": "integer",
      "minimum": 50,
      "maximum": 500,
      "default": 150,
      "description": "Maximum number of tokens for the summary."
    }
  },
  "required": ["markdown"],
  "additionalProperties": false
}
```

### Output schema (`schemas/output.json`)

```json
{
  "$id": "summarize-article-output",
  "type": "object",
  "properties": {
    "summary": {
      "type": "string",
      "description": "Plain‑text summary of the article."
    },
    "model": {
      "type": "string",
      "enum": ["gpt-4o-mini", "claude-3-haiku"],
      "description": "LLM model used for generation."
    }
  },
  "required": ["summary"],
  "additionalProperties": false
}
```

With the contract in place, any consumer can validate the payload before invoking the skill, and the skill itself can trust the shape of its inputs.

---

## Runtime adapters: Node, Python, Rust, Bash

The adapter is a thin wrapper that does three things:

1. **Start a server** (by default on `localhost:3000`) that conforms to the Stitch RPC spec.
2. **Deserialize** the incoming JSON request, validate it against the input schema, and forward the payload to the user‑provided handler.
3. **Serialize** the handler’s response, validate it against the output schema, and return it to the caller.

Below is a distilled view of the Node adapter’s entry point (`node_modules/@stitch/adapter-node/src/index.ts`):

```ts
import { createServer } from 'http';
import { validate } from '@stitch/validator';
import { handler } from '../dist/handler.js';

const PORT = process.env.PORT ?? 3000;

createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/invoke') {
    res.writeHead(404);
    return res.end();
  }

  const body = await new Promise<string>((resolve, reject) => {
    let data = '';
    req.on('data', chunk => (data += chunk));
    req.on('end', () => resolve(data));
    req.on('error', reject);
  });

  const payload = JSON.parse(body);
  const valid = validate('input', payload);
  if (!valid) {
    res.writeHead(400);
    return res.end(JSON.stringify({ error: 'Invalid input' }));
  }

  const result = await handler(payload);
  const outValid = validate('output', result);
  if (!outValid) {
    res.writeHead(500);
    return res.end(JSON.stringify({ error: 'Handler produced invalid output' }));
  }

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(result));
}).listen(PORT, () => console.log(`Stitch node adapter listening on ${PORT}`));
```

The Python and Rust adapters follow the same pattern, exposing a `/invoke` endpoint that expects a JSON body. For Bash, the adapter simply pipes JSON into a script’s stdin and reads stdout, which makes it possible to wrap existing CLI tools without any compilation step.

Because the adapters are **stateless**, you can horizontally scale them behind a load balancer, or you can run a single instance in a serverless function if the skill’s cold‑start time is acceptable.

---

## Building your first Stitch Skill

Let’s walk through a concrete example: a skill that takes a markdown article and returns a concise summary. We’ll use TypeScript for the handler because my day‑to‑day stack is Node, but the same steps apply to any language.

### 1. Scaffold the project

```bash
# From the repo root
mkdir -p skills/summarize-article
cd skills/summarize-article
npm init -y
npm i -D typescript @stitch/adapter-node @stitch/validator
npx tsc --init
```

Add the following to `tsconfig.json` to target ES2022 (required for top‑level await):

```json
{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES2022",
    "outDir": "dist",
    "esModuleInterop": true,
    "strict": true
  }
}
```

### 2. Write the handler

Create `src/handler.ts`:

```ts
import { CompletionCreateParams } from 'openai/resources/completions';
import OpenAI from 'openai';

// You can inject the model via env vars; defaults to a cheap, fast model.
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

export async function handler(input: {
  markdown: string;
  maxTokens?: number;
}): Promise<{
  summary: string;
  model: string;
}> {
  const prompt = `
You are a concise summarizer. Produce a plain‑text summary of the following markdown article, limited to ${input.maxTokens ?? 150} tokens.

---ARTICLE---
${input.markdown}
---END---
`;

  const response = await client.completions.create({
    model: process.env.MODEL ?? 'gpt-4o-mini',
    prompt,
    max_tokens: input.maxTokens ?? 150,
    temperature: 0.2,
    stop: ['---END---']
  } as CompletionCreateParams);

  const summary = response.choices[0].text?.trim() ?? '';
  return { summary, model: response.model };
}
```

> **Verification note**  
> The exact OpenAI SDK method signatures (`client.completions.create`) are based on the v4 SDK documentation. If you are using a different version, the call shape may differ.

### 3. Add the manifest

Create `stitch.json` as shown earlier, pointing `runtime.entrypoint` to `dist/handler.js`.

### 4. Build and test locally

```bash
npm run build   # runs `tsc`
npx @stitch/adapter-node   # starts the adapter on port 3000
```

In another terminal, invoke the skill with `curl`:

```bash
curl -X POST http://localhost:3000/invoke \
  -H "Content-Type: application/json" \
  -d '{"markdown":"# Intro\nLorem ipsum dolor sit amet, consectetur adipiscing elit..."}'
```

You should receive a JSON payload matching the output schema.

### 5. Publish as an npm package (optional)

If you want the skill to be consumable across multiple repositories, you can publish it to a private npm registry:

```bash
npm version 1.2.0   # bumps the manifest version as well
npm publish --access restricted
```

Consumers then add it as a dependency and run the adapter as a subprocess, e.g., `npx stitch-runtime summarize-article@1.2.0`.

---

## Plugging Stitch Skills into existing stacks

Once a skill is packaged, integrating it is a matter of **calling the `/invoke` endpoint**. Because the contract is HTTP‑based, you can use any fetch library, GraphQL resolver, or even a serverless function.

### Using the AG‑UI Protocol to expose a skill as a UI component

In a React/Next.js app that already adopts the AG‑UI Protocol, you can wrap a skill as a reusable component:

```tsx
import { useAgentSkill } from '@ag-ui/react';
import type { SummarizeArticleInput, SummarizeArticleOutput } from 'summarize-article';

export function ArticleSummarizer({ markdown }: { markdown: string }) {
  const { invoke, loading, error, result } = useAgentSkill<
    SummarizeArticleInput,
    SummarizeArticleOutput
  >('summarize-article', { maxTokens: 200 });

  React.useEffect(() => {
    invoke({ markdown });
  }, [markdown, invoke]);

  if (loading) return <p>Summarizing…</p>;
  if (error) return <p>Failed: {error.message}</p>;

  return <p>{result?.summary}</p>;
}
```

The `useAgentSkill` hook abstracts away the HTTP call and automatically validates the payload against the skill’s schemas. You can read more about wiring AG‑UI with custom agents in our post on **[Adopting the AG‑UI Protocol: Building Scalable AI Agent Interfaces in React and Next.js](/blog/adopt-ag-ui-protocol-react-nextjs/)**.

### Calling from a backend service

A Go microservice can invoke the same skill via a simple HTTP client:

```go
type SummarizeInput struct {
    Markdown   string `json:"markdown"`
    MaxTokens  int    `json:"maxTokens,omitempty"`
}
type SummarizeOutput struct {
    Summary string `json:"summary"`
    Model   string `json:"model"`
}

func SummarizeArticle(md string) (string, error) {
    payload := SummarizeInput{Markdown: md, MaxTokens: 150}
    body, _ := json.Marshal(payload)

    resp, err := http.Post("http://skill-runner:3000/invoke", "application/json", bytes.NewReader(body))
    if err != nil {
        return "", err
    }
    defer resp.Body.Close()

    var out SummarizeOutput
    if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
        return "", err
    }
    return out.Summary, nil
}
```

Because the contract is language‑agnostic, you can keep the same version of the skill across all three services. When you bump the skill to `2.0.0`, the Go service simply updates its dependency in the Docker compose file, and the React UI automatically picks up the new version after a redeploy.

---

## Versioning and backward compatibility

Stitch enforces **semantic versioning** at the manifest level. The runtime validates that the caller’s requested version satisfies the `^` (caret) range defined in the client’s configuration. For example, a client might request `"summarize-article@^1.0.0"`; the orchestrator will resolve to the highest `1.x` release that satisfies the manifest’s schema.

When you need to introduce a breaking change—say, you add a required `language` field to the input schema—you must:

1. Increment the **MAJOR** version (`1.x.x → 2.0.0`).
2. Publish a migration guide (README) that explains how callers should adapt.
3. Optionally provide a **compatibility shim** that maps the old schema to the new one, but only for a limited deprecation window.

Downstream services can adopt a **graceful fallback** strategy:

```tsx
const { invoke, result } = useAgentSkill('summarize-article@^1.0.0', { maxTokens: 200 });
```

If the orchestrator cannot find a matching version, it returns a `404` with a structured error that includes the latest compatible version. This pattern mirrors npm’s own version resolution and gives you a familiar mental model.

---

## Testing and quality gates

Because Stitch skills are just functions behind a JSON contract, you can unit‑test the handler in isolation and then run an **integration test** against the adapter.

### Unit test (Jest)

```ts
import { handler } from '../src/handler';

test('produces a non‑empty summary', async () => {
  const result = await handler({ markdown: '# Title\nContent', maxTokens: 50 });
  expect(result.summary).toBeTruthy();
  expect(result.model).toMatch(/^gpt-/);
});
```

### Integration test (SuperTest against the adapter)

```ts
import request from 'supertest';
import { spawn } from 'child_process';
import path from 'path';

let proc: ReturnType<typeof spawn>;

beforeAll(() => {
  proc = spawn('node', [path.resolve(__dirname, '../../node_modules/@stitch/adapter-node/dist/index.js')], {
    env: { ...process.env, PORT: '4000' },
    stdio: 'ignore'
  });
});

afterAll(() => proc.kill());

test('adapter validates input and output', async () => {
  const res = await request('http://localhost:4000')
    .post('/invoke')
    .send({ markdown: '# Test', maxTokens: 30 })
    .expect(200);
  expect(res.body).toHaveProperty('summary');
});
```

You can then hook these tests into a CI pipeline and enforce a **quality gate** that blocks merges if any test fails. In larger orgs we also run a schema‑validation step that checks the manifest against the official `skill-manifest.json` schema on every PR.

> **Verification note**  
> The exact CI integration steps (e.g., using GitHub Actions or GitLab CI) depend on the organization’s pipeline. The example above assumes a Node‑centric CI environment.

---

## Deployment patterns

Stitch skills can be deployed in three common ways:

| Pattern | When to use | Typical tooling |
|---|---|---|
| **Docker container** | Need isolation, custom OS libs, or GPU access | `Dockerfile` (see below) |
| **Serverless function** | Low traffic, cheap scaling, cold‑start acceptable | AWS Lambda (Node.js runtime) or Vercel Serverless Functions |
| **Self‑hosted binary** | Legacy environments, strict security zones | Bash adapter wrapping an existing CLI |

### Example Dockerfile for a Node‑based skill

```dockerfile
# syntax=docker/dockerfile:1.4
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:20-alpine AS runtime
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY stitch.json .
ENV PORT=8080
EXPOSE 8080
CMD ["node", "/app/node_modules/@stitch/adapter-node/dist/index.js"]
```

Build and push:

```bash
docker build -t registry.example.com/stitch/summarize-article:1.2.0 .
docker push registry.example.com/stitch/summarize-article:1.2.0
```

You can then reference the image in a Kubernetes `Deployment` or an ECS task definition. The orchestrator (e.g., a sidecar that runs `stitch-runtime`) will discover the container via a service registry and route calls accordingly.

---

## Observability and logging

Stitch ships with an optional **OpenTelemetry** plugin. By enabling the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable, the adapter automatically emits spans for each `/invoke` request, including:

* Request latency
* Input validation errors
* Handler‑level exceptions

In practice, I’ve wired this into a Grafana Loki stack and set up a Loki query that surfaces any skill that returns a 5xx status more than twice in a five‑minute window. The alerting rule looks like:

```promql
sum by (skill_name) (rate(http_server_requests_seconds_count{status="5xx", job="stitch-adapter"}[5m])) > 2
```

Because the logs are structured JSON, you can also forward them to a SIEM for compliance audits.

---

## Security considerations

1. **Input validation** – The validator runs *before* the handler, but you should still sanitize any data that will be passed to external APIs (e.g., URLs, file paths). Use libraries like `validator.js` for URL checks.
2. **Sandboxing** – For untrusted code (e.g., a skill contributed by a third‑party team), run the adapter inside a Docker container with `--read-only` and limited `seccomp` profiles. The Bash adapter can be further confined with `firejail`.
3. **Secret management** – Do not bake API keys into the skill’s source. Instead, inject them via environment variables or a secret manager (AWS Secrets Manager, GCP Secret Manager). The adapter will forward the environment unchanged to the handler, so you can rely on the same secret‑rotation policies you already have for your services.
4. **Network egress** – If a skill only needs to call the OpenAI endpoint, enforce egress rules at the container level to prevent accidental data exfiltration.

---

## When Stitch isn’t the right tool

Stitch excels for **stateless, request‑oriented** capabilities. However, there are scenarios where the overhead of the manifest + adapter layer becomes a liability:

* **Real‑time streaming** – If you need token‑level streaming back to the client (e.g., a live code‑completion UI), the current HTTP‑only contract forces you to buffer the entire response. You could extend Stitch with a WebSocket transport, but that’s not in the core yet.
* **Heavy GPU workloads** – Running a skill that requires a dedicated GPU in a container can be done, but the adapter adds a small Node.js process that consumes CPU cycles. In a tightly packed inference server you might prefer to call the model directly from the host process.
* **Complex orchestration** – When a skill is actually a composition of multiple micro‑services (e.g., a retrieval‑augmented generation pipeline), you might be better off defining a higher‑level workflow language (like Temporal) rather than a single Stitch skill.

In those cases, I still recommend keeping the **manifest‑first mindset**: define a JSON schema for the overall workflow, even if you don’t use Stitch’s runtime.

---

## Future directions and open questions

* **Schema evolution tooling** – Right now you manually bump the version and update the `$ref` paths. A CLI that can diff two manifests and generate a migration guide would be a huge productivity boost.
* **Streaming adapter** – Adding a `ws://` transport that streams partial JSON objects could unlock real‑time assistants without breaking existing contracts.
* **Community registry** – A public index of vetted Stitch Skills (similar to npm’s public registry) would make discovery easier, but it raises questions about licensing, provenance, and security vetting.
* **Model‑agnostic benchmarking** – I’d love to see a standard benchmark suite that measures latency, token cost, and hallucination rate *per skill*, but the variability of prompts and downstream data makes it hard to produce reproducible numbers. Until we have a community‑driven benchmark, any performance claim should be taken with a grain of salt.

---

Building modular, language‑agnostic AI agent capabilities is less about inventing a new AI model and more about **engineering the plumbing** that lets those models be reused safely across teams. Stitch gives us a concrete contract, a minimal runtime, and a versioning discipline that mirrors the best practices we already use for traditional micro‑services. It isn’t a silver bullet—especially for streaming or GPU‑bound workloads—but it does cut down the “write‑once, copy‑paste‑everywhere” pain that has haunted me for years.

If you’re already using the AG‑UI Protocol, you’ll find that stitching a skill into your UI is a matter of a few lines of code. If you’re on a more traditional backend, the same skill can be called from a Go service, a Ruby on Rails job, or a Bash script with virtually no changes. That portability is the payoff of standardizing LLM agent skills with Stitch.

## Conclusion

A skills library is a good default until your capabilities diverge from it. The moment you fork more than a couple of skills, the library has stopped saving you work and started being a dependency you maintain.

A skills library is one answer to the problem; [a unified agent skill framework](/blog/unified-agent-skill-framework/) covers the organisational version. I build and standardise these under [AI engineering](/services/ai-engineering/) and [AI agent development](/services/ai-agent-development/). For the tool description that makes a skill selectable, [Anthropic's guidance on writing tools for agents](https://www.anthropic.com/engineering/writing-tools-for-agents) is the reference. If you have forked more skills than you use, [that is worth a conversation](/contact/).

## Frequently asked questions

### When is a skills library worth adopting?

When your capabilities are common ones and the library already covers them. It saves the definition work and gives you a shared vocabulary, which is most of the value.

### What makes a skill reusable across projects?

A narrow input and output, and no assumptions about the host application. A skill that reads global state is reusable in name only.

### How should skills be versioned?

Like any dependency: a version per skill, and a changelog when behaviour changes. A skill whose behaviour shifts without a version bump breaks callers silently.

---

HTML version: https://fullstackweb.dev/blog/standardizing-llm-agent-skills-with-stitch/
Maintained by Hendra Nicholas, Senior Full-Stack Software Engineer & AI Engineer, hello@fullstackweb.dev.
