@agentspec/adapter-claude 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,372 @@
1
+ # AgentSpec → Mastra Generation Skill
2
+
3
+ You are generating production-ready TypeScript Mastra agent code from an AgentSpec manifest JSON.
4
+
5
+ ## Output Format
6
+
7
+ Return a single JSON object (wrapped in ```json ... ```) with this exact shape:
8
+
9
+ ```json
10
+ {
11
+ "files": {
12
+ "src/agent.ts": "...",
13
+ "src/tools.ts": "...",
14
+ "mastra.config.ts": "...",
15
+ "package.json": "...",
16
+ ".env.example": "...",
17
+ "README.md": "..."
18
+ },
19
+ "installCommands": [
20
+ "npm install",
21
+ "cp .env.example .env"
22
+ ],
23
+ "envVars": ["OPENAI_API_KEY", "LANGFUSE_PUBLIC_KEY"]
24
+ }
25
+ ```
26
+
27
+ **File generation rules:**
28
+ | File | When to generate |
29
+ |---|---|
30
+ | `src/agent.ts` | Always |
31
+ | `src/tools.ts` | When `spec.tools` is non-empty |
32
+ | `mastra.config.ts` | Always |
33
+ | `package.json` | Always |
34
+ | `.env.example` | Always |
35
+ | `README.md` | Always |
36
+
37
+ **Invariants:**
38
+ - Map **every** manifest field. Do not skip sections.
39
+ - All string values embedded in TypeScript code must be properly escaped.
40
+ - Never embed literal API keys — always use `process.env.VAR_NAME`.
41
+ - Validate required env vars at startup with a `validateEnv()` function.
42
+
43
+ ---
44
+
45
+ ## Reference Syntax Resolution
46
+
47
+ Resolve `$ref` values before generating TypeScript:
48
+
49
+ | Manifest reference | TypeScript |
50
+ |---|---|
51
+ | `$env:VAR_NAME` | `process.env.VAR_NAME` |
52
+ | `$env:VAR_NAME` (required) | `process.env.VAR_NAME` — list in `REQUIRED_ENV_VARS` |
53
+ | `$secret:secret-name` | `process.env.AGENTSPEC_SECRET_SECRET_NAME` — transform: uppercase, `-` → `_`, prefix `AGENTSPEC_SECRET_` |
54
+ | `$file:path/to/file` | `fs.readFileSync(path.join(__dirname, 'path/to/file'), 'utf-8')` |
55
+ | `$func:now_iso` | `new Date().toISOString()` |
56
+
57
+ Examples:
58
+ - `$secret:langfuse-secret-key` → `process.env.AGENTSPEC_SECRET_LANGFUSE_SECRET_KEY`
59
+ - `$env:OPENAI_API_KEY` → `process.env.OPENAI_API_KEY`
60
+
61
+ ---
62
+
63
+ ## Mapping Rules
64
+
65
+ ### spec.model — AI SDK provider
66
+
67
+ | Manifest field | TypeScript |
68
+ |---|---|
69
+ | `provider: openai` | `import { openai } from '@ai-sdk/openai'` |
70
+ | `provider: anthropic` | `import { anthropic } from '@ai-sdk/anthropic'` |
71
+ | `provider: google` | `import { google } from '@ai-sdk/google'` |
72
+ | `provider: groq` | `import { createGroq } from '@ai-sdk/groq'` |
73
+ | `provider: mistral` | `import { mistral } from '@ai-sdk/mistral'` |
74
+ | `id` | First argument to provider function: `openai('gpt-4o')` |
75
+ | `parameters.temperature` | `temperature: N` in `generate` / agent options |
76
+ | `parameters.maxTokens` | `maxTokens: N` in generate options |
77
+ | `apiKey: $env:VAR` | `apiKey: process.env.VAR` in provider factory options |
78
+
79
+ ### spec.prompts
80
+
81
+ ```typescript
82
+ import * as fs from 'fs'
83
+ import * as path from 'path'
84
+
85
+ function loadSystemPrompt(): string {
86
+ try {
87
+ const template = fs.readFileSync(
88
+ path.join(__dirname, '../prompts/system.md'),
89
+ 'utf-8'
90
+ )
91
+ const variables: Record<string, string> = {
92
+ unit_system: process.env.UNIT_SYSTEM ?? '',
93
+ current_date: new Date().toISOString(),
94
+ }
95
+ return Object.entries(variables).reduce(
96
+ (t, [k, v]) => t.replaceAll(`{{ ${k} }}`, v),
97
+ template
98
+ )
99
+ } catch {
100
+ return "I'm experiencing difficulties. Please try again."
101
+ }
102
+ }
103
+ ```
104
+
105
+ For `hotReload: true` — call `loadSystemPrompt()` on every agent invocation (no module-level caching).
106
+
107
+ ### spec.tools — src/tools.ts
108
+
109
+ ```typescript
110
+ import { createTool } from '@mastra/core'
111
+ import { z } from 'zod'
112
+
113
+ export const logWorkout = createTool({
114
+ id: 'log_workout',
115
+ description: 'Log a completed training session with exercises, sets, reps, and duration',
116
+ inputSchema: z.object({
117
+ input: z.string().describe('Tool input'),
118
+ }),
119
+ execute: async ({ context }) => {
120
+ throw new Error('Implement logWorkout')
121
+ },
122
+ })
123
+
124
+ export const getWorkoutHistory = createTool({
125
+ id: 'get_workout_history',
126
+ description: 'Retrieve past training sessions with optional filters',
127
+ inputSchema: z.object({
128
+ input: z.string().describe('Tool input'),
129
+ }),
130
+ execute: async ({ context }) => {
131
+ throw new Error('Implement getWorkoutHistory')
132
+ },
133
+ })
134
+ ```
135
+
136
+ Rules:
137
+ - Tool `id`: `tool.function` if set, otherwise `snake_case(tool.name)`
138
+ - Export name: `camelCase(tool.name)`
139
+ - `description`: `tool.description`
140
+ - `execute` body: `throw new Error('Implement {camelCaseName}')`
141
+ - Input schema: `z.object({ input: z.string() })` as a sensible default
142
+
143
+ **src/agent.ts imports tools:**
144
+ ```typescript
145
+ import { logWorkout, getWorkoutHistory } from './tools.js'
146
+ const tools = { logWorkout, getWorkoutHistory }
147
+ ```
148
+
149
+ ### spec.memory
150
+
151
+ ```typescript
152
+ import { Memory } from '@mastra/core/memory'
153
+ import { LibSQLStore } from '@mastra/libsql'
154
+
155
+ const memory = new Memory({
156
+ storage: new LibSQLStore({
157
+ url: process.env.LIBSQL_URL ?? 'file:./agent.db',
158
+ }),
159
+ })
160
+ ```
161
+
162
+ Pass to agent: `new Agent({ ..., memory })`.
163
+
164
+ For `spec.memory.shortTerm.backend = "redis"`:
165
+ ```typescript
166
+ // Redis-backed memory: configure REDIS_URL for Mastra's KV store
167
+ // See Mastra docs for RedisStore integration
168
+ ```
169
+
170
+ ### spec.observability
171
+
172
+ For Langfuse:
173
+ ```typescript
174
+ // ── Tracing: Langfuse ─────────────────────────────────────────────────────────
175
+ // Mastra supports OpenTelemetry natively in mastra.config.ts
176
+ // Set LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY for automatic tracing
177
+ ```
178
+
179
+ In `mastra.config.ts`:
180
+ ```typescript
181
+ import { Mastra } from '@mastra/core'
182
+
183
+ export const mastra = new Mastra({
184
+ agents: { myAgent },
185
+ telemetry: {
186
+ serviceName: '{service_name}', // from spec.observability.serviceName
187
+ enabled: true,
188
+ },
189
+ })
190
+ ```
191
+
192
+ ### spec.requires
193
+
194
+ ```typescript
195
+ const REQUIRED_ENV_VARS = ['OPENAI_API_KEY'] // from spec.requires.envVars[]
196
+
197
+ function validateEnv(): void {
198
+ const missing = REQUIRED_ENV_VARS.filter(v => !process.env[v])
199
+ if (missing.length > 0) {
200
+ throw new Error(
201
+ `Missing required environment variables: ${missing.join(', ')}\n` +
202
+ 'Copy .env.example to .env and fill in the values.'
203
+ )
204
+ }
205
+ }
206
+
207
+ validateEnv()
208
+ ```
209
+
210
+ ---
211
+
212
+ ## Complete src/agent.ts Structure
213
+
214
+ Generate sections in this exact order:
215
+
216
+ 1. **Imports**:
217
+ - `import { Agent } from '@mastra/core'`
218
+ - `import { Memory } from '@mastra/core/memory'` (if `spec.memory` is set)
219
+ - `import { LibSQLStore } from '@mastra/libsql'` (if memory with libsql)
220
+ - Provider import from `@ai-sdk/*`
221
+ - Tool imports: `import { toolA, toolB } from './tools.js'` (if tools exist)
222
+ - `import * as fs from 'fs'` and `import * as path from 'path'` (if `$file:` refs)
223
+ 2. **Env var validation** (`validateEnv()` definition and call)
224
+ 3. **System prompt loading** (with variable interpolation if variables defined)
225
+ 4. **LLM model setup**: `const model = openai('gpt-4o')`
226
+ 5. **Memory setup** (if `spec.memory` is set)
227
+ 6. **Agent definition**:
228
+ ```typescript
229
+ export const myAgent = new Agent({
230
+ name: '{agent_name}',
231
+ instructions: loadSystemPrompt(),
232
+ model,
233
+ tools: { toolA, toolB },
234
+ memory, // if spec.memory is set
235
+ })
236
+ ```
237
+ 7. **`runAgent()` helper**:
238
+ ```typescript
239
+ export async function runAgent(userInput: string, threadId = 'default'): Promise<string> {
240
+ const result = await myAgent.generate(userInput, {
241
+ threadId,
242
+ resourceId: 'user',
243
+ })
244
+ return result.text
245
+ }
246
+ ```
247
+ 8. **`main()` block**:
248
+ ```typescript
249
+ if (import.meta.url === new URL(process.argv[1], 'file://').href) {
250
+ const input = process.argv[2] ?? 'Hello, what can you help me with?'
251
+ runAgent(input).then(console.log).catch(console.error)
252
+ }
253
+ ```
254
+
255
+ ---
256
+
257
+ ## mastra.config.ts Structure
258
+
259
+ ```typescript
260
+ import { Mastra } from '@mastra/core'
261
+ import { myAgent } from './src/agent.js'
262
+
263
+ export const mastra = new Mastra({
264
+ agents: { myAgent },
265
+ telemetry: {
266
+ serviceName: '{service_name}',
267
+ enabled: true,
268
+ },
269
+ })
270
+ ```
271
+
272
+ ---
273
+
274
+ ## package.json Template
275
+
276
+ ```json
277
+ {
278
+ "name": "{agent-name-kebab}",
279
+ "version": "{version}",
280
+ "description": "{description}",
281
+ "type": "module",
282
+ "scripts": {
283
+ "start": "tsx src/agent.ts",
284
+ "dev": "tsx --watch src/agent.ts",
285
+ "build": "tsc",
286
+ "typecheck": "tsc --noEmit"
287
+ },
288
+ "dependencies": {
289
+ "@mastra/core": "^0.10.0",
290
+ "@mastra/libsql": "^0.10.0",
291
+ "@ai-sdk/openai": "^1.0.0",
292
+ "zod": "^3.23.0"
293
+ },
294
+ "devDependencies": {
295
+ "typescript": "^5.7.0",
296
+ "tsx": "^4.19.0",
297
+ "@types/node": "^20.17.0"
298
+ }
299
+ }
300
+ ```
301
+
302
+ Provider package map:
303
+ | provider | package |
304
+ |---|---|
305
+ | `openai` | `@ai-sdk/openai` |
306
+ | `anthropic` | `@ai-sdk/anthropic` |
307
+ | `google` | `@ai-sdk/google` |
308
+ | `groq` | `@ai-sdk/groq` |
309
+ | `mistral` | `@ai-sdk/mistral` |
310
+
311
+ Add `langfuse` if `spec.observability.tracing.backend === 'langfuse'`.
312
+
313
+ ---
314
+
315
+ ## .env.example Rules
316
+
317
+ - One line per env var referenced in the manifest
318
+ - Strip `$env:` prefix for the variable name
319
+ - For `$secret:name`, the env var is `AGENTSPEC_SECRET_NAME` (uppercase, `-`→`_`)
320
+ - Add a comment describing what each var is for
321
+ - Group by concern: model, memory, observability, agent config
322
+
323
+ ---
324
+
325
+ ## README.md Template
326
+
327
+ ```markdown
328
+ # {agent_name}
329
+
330
+ {description}
331
+
332
+ **Generated by [AgentSpec](https://agentspec.io) v{version}**
333
+
334
+ ## Stack
335
+
336
+ | Component | Value |
337
+ |-----------|-------|
338
+ | Framework | Mastra |
339
+ | Model | {provider}/{model_id} |
340
+ | Memory | {memory_backend} |
341
+ | Tracing | {tracing_backend} |
342
+ | Tools | {tools_count} |
343
+
344
+ ## Quick Start
345
+
346
+ ```bash
347
+ npm install
348
+ cp .env.example .env # fill in your API keys
349
+ npm start "Hello, what can you help me with?"
350
+ ```
351
+
352
+ ## Tools
353
+
354
+ {tool_list}
355
+
356
+ ## Environment Variables
357
+
358
+ {env_var_list}
359
+ ```
360
+
361
+ ---
362
+
363
+ ## Quality Checklist
364
+
365
+ | Check | Verify |
366
+ |---|---|
367
+ | `$secret:` resolution | `$secret:langfuse-secret-key` → `AGENTSPEC_SECRET_LANGFUSE_SECRET_KEY` |
368
+ | No literal keys | Search generated code for `sk-`, `pk-`, raw key strings |
369
+ | `validateEnv()` called | At module top-level, before any connections |
370
+ | `src/tools.ts` generated | When `spec.tools` is non-empty |
371
+ | package.json complete | All `@ai-sdk/*` and `@mastra/*` packages match imports |
372
+ | ESM imports | All local imports end with `.js` extension |
@@ -0,0 +1,195 @@
1
+ # AgentSpec Scan Skill
2
+
3
+ You are analysing source code to produce a valid `agent.yaml` manifest.
4
+
5
+ The caller will provide one or more source files embedded in the context.
6
+ Your job is to extract everything the agent declares and express it as
7
+ a complete `agent.yaml` that conforms to the AgentSpec v1 schema.
8
+
9
+ ---
10
+
11
+ ## Output Format
12
+
13
+ Respond with **exactly one JSON object** in this shape:
14
+
15
+ ```json
16
+ {
17
+ "files": {
18
+ "agent.yaml": "<full YAML content as a string>"
19
+ },
20
+ "installCommands": [],
21
+ "envVars": ["OPENAI_API_KEY", "..."]
22
+ }
23
+ ```
24
+
25
+ - The `agent.yaml` value must be a valid YAML string (escape `\n` as literal newlines inside the JSON string value).
26
+ - Do NOT include any text outside the JSON object.
27
+ - Do NOT truncate the YAML.
28
+
29
+ ---
30
+
31
+ ## Detection Rules
32
+
33
+ Work through the source files and detect:
34
+
35
+ ### 1. Model
36
+
37
+ | Pattern | Meaning |
38
+ |---------|---------|
39
+ | `import openai` / `from openai import` | provider: openai |
40
+ | `import anthropic` / `from anthropic import` | provider: anthropic |
41
+ | `from langchain_openai import` | provider: openai |
42
+ | `from langchain_anthropic import` | provider: anthropic |
43
+ | `from langchain_groq import` | provider: groq |
44
+ | `OpenAI(model="…")` | model.name |
45
+ | `ChatOpenAI(model_name="…")` | model.name |
46
+ | `Anthropic(model="…")` | model.name |
47
+ | `os.getenv("OPENAI_API_KEY")` | model.apiKey: $env:OPENAI_API_KEY |
48
+ | `os.getenv("ANTHROPIC_API_KEY")` | model.apiKey: $env:ANTHROPIC_API_KEY |
49
+ | `process.env.OPENAI_API_KEY` | model.apiKey: $env:OPENAI_API_KEY |
50
+
51
+ ### 2. Tools
52
+
53
+ | Pattern | Meaning |
54
+ |---------|---------|
55
+ | `@tool` decorator on a function | add to spec.tools[] |
56
+ | `Tool(name="…", func=…)` | add to spec.tools[] |
57
+ | `StructuredTool.from_function(name="…")` | add to spec.tools[] |
58
+ | `tools = [ToolClass()]` or similar | add each detected tool |
59
+
60
+ For each tool, extract:
61
+ - `name`: the function or tool name (snake_case)
62
+ - `description`: the docstring or `description=` argument
63
+
64
+ ### 3. MCP Servers
65
+
66
+ | Pattern | Meaning |
67
+ |---------|---------|
68
+ | `MCPClient(…)` | add to spec.mcp[] |
69
+ | `mcp_servers = [{"url": "…"}]` | add each to spec.mcp[] |
70
+
71
+ ### 4. Guardrails
72
+
73
+ | Pattern | Meaning |
74
+ |---------|---------|
75
+ | Content filter / moderation call | spec.guardrails.content_filter.enabled: true |
76
+ | Rate limiter class or decorator | spec.guardrails.rate_limit.enabled: true |
77
+ | Output validator / schema check | spec.guardrails.output_validator.enabled: true |
78
+ | PII scrubbing library import | spec.guardrails.pii_scrubber.enabled: true |
79
+
80
+ ### 5. Evaluation Hooks
81
+
82
+ | Pattern | Meaning |
83
+ |---------|---------|
84
+ | `import deepeval` | spec.eval.hooks: [deepeval] |
85
+ | `import pytest` + eval functions | spec.eval.hooks: [pytest] |
86
+ | Custom eval class | spec.eval.hooks: [custom] |
87
+
88
+ ### 6. Required Environment Variables
89
+
90
+ Scan for all:
91
+ - `os.getenv("VAR_NAME")` / `os.environ["VAR_NAME"]`
92
+ - `process.env.VAR_NAME`
93
+ - `$env:VAR_NAME`
94
+
95
+ Collect unique names and list them in `spec.requires.env[]` AND in `envVars` in your JSON response.
96
+
97
+ ### 7. Memory Backend
98
+
99
+ | Pattern | Meaning |
100
+ |---------|---------|
101
+ | Redis import + connection | spec.memory.backend: redis |
102
+ | pgvector / psycopg import | spec.memory.backend: postgres |
103
+ | Pinecone / Weaviate / Qdrant | spec.memory.backend: vector-<name> |
104
+ | SQLite | spec.memory.backend: sqlite |
105
+
106
+ ### 8. Services (Databases, APIs)
107
+
108
+ | Pattern | Meaning |
109
+ |---------|---------|
110
+ | DB connection string env var | spec.requires.services[].name: database |
111
+ | External API base URL pattern | spec.requires.services[].name: <api-name> |
112
+
113
+ ### 9. Compliance Estimate
114
+
115
+ Count detected fields and estimate a compliance score (0–100):
116
+
117
+ | Detected | Score contribution |
118
+ |----------|-------------------|
119
+ | model.provider + apiKey | +20 |
120
+ | tools (at least 1) | +10 |
121
+ | guardrails.content_filter | +15 |
122
+ | guardrails.rate_limit | +10 |
123
+ | eval.hooks (at least 1) | +15 |
124
+ | memory backend | +10 |
125
+ | requires.env (at least 1) | +5 |
126
+ | observability.metrics | +10 |
127
+ | observability.tracing | +5 |
128
+
129
+ Include the estimate as a comment at the top of the generated YAML:
130
+ `# Compliance estimate: <score>/100`
131
+
132
+ ---
133
+
134
+ ## Output Schema
135
+
136
+ Generate a `agent.yaml` with this structure (include only sections that have detected values):
137
+
138
+ ```yaml
139
+ # Compliance estimate: <N>/100
140
+ # Generated by agentspec scan — review and adjust before committing
141
+
142
+ agentspec: v1
143
+
144
+ metadata:
145
+ name: <detected-or-inferred-agent-name>
146
+ description: <one-line description inferred from the code>
147
+ version: 0.1.0
148
+
149
+ spec:
150
+ model:
151
+ provider: <openai|anthropic|groq|...>
152
+ name: <model-id>
153
+ apiKey: $env:<API_KEY_VAR>
154
+
155
+ tools:
156
+ - name: <tool_name>
157
+ description: <tool description>
158
+
159
+ # (only if MCP detected)
160
+ mcp:
161
+ - name: <mcp-server-name>
162
+ url: $env:<MCP_URL_VAR>
163
+
164
+ # (only if guardrails detected)
165
+ guardrails:
166
+ content_filter:
167
+ enabled: true
168
+ rate_limit:
169
+ enabled: true
170
+
171
+ # (only if memory detected)
172
+ memory:
173
+ backend: <redis|postgres|...>
174
+ url: $env:<MEMORY_URL_VAR>
175
+
176
+ # (only if eval detected)
177
+ eval:
178
+ hooks:
179
+ - <deepeval|pytest|...>
180
+
181
+ requires:
182
+ env:
183
+ - <VAR_NAME>
184
+ ```
185
+
186
+ ---
187
+
188
+ ## Important Rules
189
+
190
+ 1. If a value cannot be detected, omit the field (never guess API keys or URLs).
191
+ 2. All secrets and API keys MUST use `$env:VAR_NAME` syntax — never hardcode values.
192
+ 3. The agent name should be snake_case, inferred from the file or class name.
193
+ 4. If no source files are provided, generate a minimal valid manifest with a comment
194
+ explaining that no source was available.
195
+ 5. Always include at least `agentspec: v1`, `metadata.name`, and `spec.model` in the output.
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@agentspec/adapter-claude",
3
+ "version": "0.1.0",
4
+ "description": "AgentSpec agentic adapter — uses Claude API to generate complete agent code from agent.yaml",
5
+ "author": "Sallah Kokaina <sallah.kokaina@gmail.com>",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://agentspec.io",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/agents-oss/agentspec.git",
11
+ "directory": "packages/adapter-claude"
12
+ },
13
+ "bugs": { "url": "https://github.com/agents-oss/agentspec/issues" },
14
+ "keywords": ["ai-agents", "agent-manifest", "claude", "anthropic", "agentspec", "code-generation"],
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "import": "./dist/index.js",
21
+ "types": "./dist/index.d.ts"
22
+ }
23
+ },
24
+ "files": ["dist"],
25
+ "scripts": {
26
+ "build": "tsup && mkdir -p dist/skills && cp src/skills/*.md dist/skills/",
27
+ "dev": "tsup --watch",
28
+ "test": "vitest run",
29
+ "typecheck": "tsc --noEmit",
30
+ "lint": "tsc --noEmit",
31
+ "clean": "rm -rf dist",
32
+ "prepublishOnly": "pnpm build"
33
+ },
34
+ "dependencies": {
35
+ "@agentspec/sdk": "workspace:*",
36
+ "@anthropic-ai/sdk": "^0.36.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^20.17.0",
40
+ "tsup": "^8.3.5",
41
+ "typescript": "^5.7.2",
42
+ "vitest": "^2.1.8"
43
+ }
44
+ }