[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GVB29MZ2KB9NZX926R2BZD":3,"skill-same:01M6GVB29MZ2KB9NZX926R2BZD":85},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":6,"ownerHtmlUrl":53,"ownerBlogUrl":54,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M6GVB29MZ2KB9NZX926R2BZD","add-test",null,"Scaffold a test file for an existing tool, resource, or service. Use when the user asks to add tests, improve coverage, or when a definition exists without a matching test file.","jiayaoqijia\u002Fcryptoskill","jiayaoqijia","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1453879?v=4","01M6GMYTX7Q7S504VC6E756ENR","YQ","01M6GMYV1QKJ1CC75MTTGT9PR0",81,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-add-test\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-add-test\u002FSKILL.md",[],[20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"add test","add","test","reference","when","definition","Existing","for","tests","service","matching","use","coverage","user","tool","improve","file","scaffold","2026-11-10 10:12:30",false,"---\nname: add-test\ndescription: >\n  Scaffold a test file for an existing tool, resource, or service. Use when the user asks to add tests, improve coverage, or when a definition exists without a matching test file.\nmetadata:\n  author: cyanheads\n  version: \"1.9\"\n  audience: external\n  type: reference\n---\n\n## Context\n\nTests use Vitest and `createMockContext` from `@cyanheads\u002Fmcp-ts-core\u002Ftesting`. If the repo already has tests, match the existing layout. If the repo has no existing tests, create a root `tests\u002F` directory that mirrors the `src\u002F` structure (e.g. `tests\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002Fecho.tool.test.ts` for `src\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002Fecho.tool.ts`).\n\nFor the full `createMockContext` API and testing patterns, read:\n\n    framework-skills\u002Fapi-testing\u002FSKILL.md\n\n## Steps\n\n1. **Identify the target** — which tool, resource, or service needs tests\n2. **Read the source file** — understand the handler's logic, input\u002Foutput schemas, error paths, and which `ctx` features it uses\n3. **Create the test file** in the repo's existing test layout — search for existing `*.test.ts` files to confirm whether tests are colocated with source or under a root `tests\u002F` directory\n4. **Write test cases** covering happy path, error paths, and edge cases\n5. **Run `bun run test`** to verify\n6. **Run `bun run devcheck`** to verify lint, types, and MCP definitions\n\n## Determining What to Test\n\nRead the handler and identify:\n\n| Aspect | Test Strategy |\n|:-------|:-------------|\n| **Happy path** | Valid input → expected output. Include at least one. |\n| **Input variations** | Optional fields omitted, defaults applied, boundary values |\n| **Error paths** | Invalid state, missing resources, service failures → correct error thrown |\n| **`ctx.state` usage** | Available on any mock context (tenant `'default'` unless `{ tenantId }` says otherwise). It runs the production storage path, so use storage-legal keys (`cache\u002Fv1\u002Fabc`, never `cache:v1:abc`) and assert TTL expiry with fake timers. |\n| **`ctx.requestInput` \u002F `ctx.inputs`** | Two rounds. First round: assert the handler throws the input-required signal (`.rejects.toSatisfy(isInputRequiredSignal)`), or catch it and assert on `error.result.inputRequests`. Second round: seed `createMockContext({ inputResponses })` and assert the handler completes. Cover the decline\u002Fcancel branch too. A consent gate that redeems a `ctx.state` record also needs that record written into the second round's context, and a replay case showing the spent record asks again (see `api-testing` § Mock inputs). |\n| **`ctx.clientCapabilities`** | When the handler asks only if the client declared a capability, seed `createMockContext({ clientCapabilities })` with and without it and assert it asks in one case and falls through in the other. Seeding it also filters `inputResponses` to the declared kinds, as production does. |\n| **`ctx.signal`** | Pass `createMockContext({ signal: controller.signal })` and assert a long loop stops early rather than running to completion. |\n| **`ctx.fail` (typed contract)** | Definitions with `errors[]` need `fail` attached to the mock ctx — `createMockContext({ errors: myTool.errors })` does it for you. Assert on `data.reason` (stable per-contract entry), not just `code`. |\n| **`format` function** | Test separately if defined — it's pure, no ctx needed. Verify it renders the IDs and fields the model needs, not just a count or title. For projection-style tools, test non-default field selections. |\n| **Sparse upstream payloads** | For third-party API integrations, build a fixture with omitted fields. Assert normalized output still validates and `format()` preserves unknown values instead of inventing facts. |\n| **Form-client payloads** | If handler has optional fields: test with empty-string inner values (form clients send `\"\"` instead of `undefined`). Assert handler doesn't break or produce invalid output. |\n| **Auth scopes** | Not tested at handler level (framework enforces) — skip |\n\n## Templates\n\n### Tool test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{TOOL_NAME}} tool.\n * @module tests\u002Ftools\u002F{{TOOL_NAME}}.tool.test\n *\u002F\n\nimport { describe, expect, it } from 'vitest';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\nimport { {{TOOL_EXPORT}} } from '@\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002F{{tool-name}}.tool.js';\n\ndescribe('{{TOOL_EXPORT}}', () => {\n  it('returns expected output for valid input', async () => {\n    const ctx = createMockContext();\n    const input = {{TOOL_EXPORT}}.input.parse({\n      \u002F\u002F valid input matching the Zod schema\n    });\n    const result = await {{TOOL_EXPORT}}.handler(input, ctx);\n    expect(result).toMatchObject({\n      \u002F\u002F expected output shape\n    });\n  });\n\n  it('throws on invalid state', async () => {\n    const ctx = createMockContext();\n    const input = {{TOOL_EXPORT}}.input.parse({\n      \u002F\u002F input that triggers an error path\n    });\n    await expect({{TOOL_EXPORT}}.handler(input, ctx)).rejects.toThrow();\n  });\n\n  \u002F\u002F Only when the tool declares `errors: [...]`. Drop this block otherwise.\n  it('throws ctx.fail(\"{{REASON}}\") for the declared failure mode', async () => {\n    const ctx = createMockContext({ errors: {{TOOL_EXPORT}}.errors });\n    const input = {{TOOL_EXPORT}}.input.parse({\n      \u002F\u002F input that triggers the declared failure mode\n    });\n    await expect({{TOOL_EXPORT}}.handler(input, ctx)).rejects.toMatchObject({\n      data: { reason: '{{REASON}}' },\n    });\n  });\n\n  it('formats output completely', () => {\n    const output = { \u002F* mock output matching the output schema *\u002F };\n    const blocks = {{TOOL_EXPORT}}.format!(output);\n    expect(blocks.some((block) => block.type === 'text')).toBe(true);\n    \u002F\u002F Assert the rendered text includes the IDs\u002Ffields the LLM needs to act on.\n  });\n});\n```\n\n### Resource test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{RESOURCE_NAME}} resource.\n * @module tests\u002Fresources\u002F{{RESOURCE_NAME}}.resource.test\n *\u002F\n\nimport { describe, expect, it } from 'vitest';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\nimport { {{RESOURCE_EXPORT}} } from '@\u002Fmcp-server\u002Fresources\u002Fdefinitions\u002F{{resource-name}}.resource.js';\n\ndescribe('{{RESOURCE_EXPORT}}', () => {\n  it('returns data for valid params', async () => {\n    const ctx = createMockContext({ tenantId: 'test-tenant' });\n    const params = {{RESOURCE_EXPORT}}.params.parse({\n      \u002F\u002F valid params matching the Zod schema\n    });\n    const result = await {{RESOURCE_EXPORT}}.handler(params, ctx);\n    expect(result).toBeDefined();\n  });\n\n  it('throws when resource not found', async () => {\n    const ctx = createMockContext({ tenantId: 'test-tenant' });\n    const params = {{RESOURCE_EXPORT}}.params.parse({\n      \u002F\u002F params for a non-existent resource\n    });\n    await expect({{RESOURCE_EXPORT}}.handler(params, ctx)).rejects.toThrow();\n  });\n\n  \u002F\u002F For resources that declare an `errors: [...]` contract, pass the contract via\n  \u002F\u002F `createMockContext` so the typed `ctx.fail` is wired automatically:\n  \u002F\u002F   const ctx = createMockContext({ errors: {{RESOURCE_EXPORT}}.errors });\n  \u002F\u002F   const err = await {{RESOURCE_EXPORT}}.handler(params, ctx).catch((e) => e);\n  \u002F\u002F   expect(err.code).toBe(JsonRpcErrorCode.NotFound);\n  \u002F\u002F   expect(err.data.reason).toBe('no_match');\n\n  \u002F\u002F Include this block only when the resource definition exports a `list` function.\n  \u002F\u002F Check the source — `list` is optional on resource definitions.\n  it('lists available resources', async () => {\n    const listing = await {{RESOURCE_EXPORT}}.list!();\n    expect(listing.resources).toBeInstanceOf(Array);\n    expect(listing.resources.length).toBeGreaterThan(0);\n    for (const r of listing.resources) {\n      expect(r).toHaveProperty('uri');\n      expect(r).toHaveProperty('name');\n    }\n  });\n});\n```\n\n### Service test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{SERVICE_NAME}} service.\n * @module tests\u002Fservices\u002F{{domain}}\u002F{{domain}}-service.test\n *\u002F\n\nimport { beforeEach, describe, expect, it } from 'vitest';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\nimport { StorageService } from '@cyanheads\u002Fmcp-ts-core\u002Fstorage';\nimport { get{{ServiceClass}}, init{{ServiceClass}} } from '@\u002Fservices\u002F{{domain}}\u002F{{domain}}-service.js';\n\n\u002F\u002F Derive the minimal mock config from src\u002Fconfig\u002Fserver-config.ts — read\n\u002F\u002F the server's Zod schema to see which fields init{{ServiceClass}}() needs.\nconst mockConfig = { \u002F* fields from server config schema *\u002F } as AppConfig;\n\ndescribe('{{ServiceClass}}', () => {\n  beforeEach(async () => {\n    const mockStorage = await StorageService.create({ type: 'in-memory' });\n    init{{ServiceClass}}(mockConfig, mockStorage);\n  });\n\n  it('performs the expected operation', async () => {\n    const ctx = createMockContext({ tenantId: 'test-tenant' });\n    const service = get{{ServiceClass}}();\n    const result = await service.doWork('input', ctx);\n    expect(result).toBeDefined();\n  });\n});\n```\n\nIf you need to test the accessor's \"not initialized\" guard, do it in a separate isolated-module test (`vi.resetModules()` before importing the service module). Don't mix that assertion into a suite that already calls `init{{ServiceClass}}()` in `beforeEach()`.\n\n### Multi-round-trip tool test\n\nA handler that calls `ctx.requestInput(...)` throws an `InputRequiredSignal` — in production the handler factory converts it to an `input_required` result; in a unit test it surfaces as a thrown value. Test both rounds.\n\n```typescript\nimport { isInputRequiredSignal } from '@cyanheads\u002Fmcp-ts-core';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\n\nit('requests the missing input on the first round', async () => {\n  const ctx = createMockContext();\n  const input = {{TOOL_EXPORT}}.input.parse({ path: '\u002Ftmp\u002Fx' });\n\n  try {\n    await {{TOOL_EXPORT}}.handler(input, ctx);\n    throw new Error('Expected the handler to request input.');\n  } catch (error) {\n    if (!isInputRequiredSignal(error)) throw error;\n    expect(Object.keys(error.result.inputRequests ?? {})).toEqual(['confirm']);\n  }\n});\n\nit('completes once the response is supplied', async () => {\n  const ctx = createMockContext({\n    inputResponses: { confirm: { action: 'accept', content: { confirm: true } } },\n  });\n  const input = {{TOOL_EXPORT}}.input.parse({ path: '\u002Ftmp\u002Fx' });\n\n  await expect({{TOOL_EXPORT}}.handler(input, ctx)).resolves.toMatchObject({ deleted: '\u002Ftmp\u002Fx' });\n});\n\nit('does not re-ask after a decline', async () => {\n  const ctx = createMockContext({ inputResponses: { confirm: { action: 'decline' } } });\n  const input = {{TOOL_EXPORT}}.input.parse({ path: '\u002Ftmp\u002Fx' });\n\n  \u002F\u002F Terminal, not another round — re-asking would burn the round budget.\n  await expect({{TOOL_EXPORT}}.handler(input, ctx)).rejects.toThrow(McpError);\n});\n```\n\nFor a destructive consent gate, the second round completes only when the context holds the single-use record the first round stored, keyed by the `requestState` it returned — each mock context has its own `ctx.state`, so write the record into the second context before calling the handler. `api-testing` § Mock inputs has the full pattern, including the replay case.\n\n### Cancellation test\n\nPass an `AbortController` signal through `createMockContext` or `runToolContract`.\nAbort after a controlled I\u002FO operation or loop iteration starts, then assert that\nthe pending call settles and no further requests or iterations run. Use a deferred\nfixture or fake timers so the test does not depend on a wall-clock delay; restore\ntimers and close any fixture resources afterward. A defined result alone does not\nprove cancellation stopped the work.\n\nWhen an abort-aware handler throws after the signal fires, `runToolContract` returns\n`isError: true` with `structuredContent.error.code` equal to\n`JsonRpcErrorCode.RequestCancelled`; assert the cancellation message in `content[]`\nas well. Use schema-valid arguments: invalid arguments still return `InvalidParams`\nbefore the handler runs. A partial success is appropriate only when the tool's\ncontract explicitly supports it; assert its actual partial-result fields, output\nschema, and `format()` content instead of requiring every handler to return one.\n\n### Prompt test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{PROMPT_NAME}} prompt.\n * @module tests\u002Fprompts\u002F{{PROMPT_NAME}}.prompt.test\n *\u002F\n\nimport { describe, expect, it } from 'vitest';\nimport { {{PROMPT_EXPORT}} } from '@\u002Fmcp-server\u002Fprompts\u002Fdefinitions\u002F{{prompt-name}}.prompt.js';\n\ndescribe('{{PROMPT_EXPORT}}', () => {\n  it('generates valid messages for valid args', () => {\n    const args = {{PROMPT_EXPORT}}.args!.parse({\n      \u002F\u002F valid args matching the Zod schema\n    });\n    const messages = {{PROMPT_EXPORT}}.generate(args);\n    expect(messages).toBeInstanceOf(Array);\n    expect(messages.length).toBeGreaterThan(0);\n    for (const msg of messages) {\n      expect(msg).toHaveProperty('role');\n      expect(msg).toHaveProperty('content');\n    }\n  });\n\n  \u002F\u002F Include only when the prompt has no required args (args is optional or all fields optional).\n  it('generates messages with no args', () => {\n    const messages = {{PROMPT_EXPORT}}.generate({});\n    expect(messages.length).toBeGreaterThan(0);\n  });\n});\n```\n\n## Fuzz Testing\n\nFor schema-heavy or input-validation-critical handlers, the framework ships fuzz helpers that generate valid + adversarial inputs from your Zod schemas via `fast-check` and assert handler invariants (no crashes, no prototype pollution, no stack-trace leaks):\n\n```typescript\nimport { fuzzTool } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting\u002Ffuzz';\n\nit('survives fuzz testing', async () => {\n  const report = await fuzzTool({{TOOL_EXPORT}}, { numRuns: 100 });\n  expect(report.crashes).toHaveLength(0);\n  expect(report.leaks).toHaveLength(0);\n  expect(report.prototypePollution).toBe(false);\n});\n```\n\nAvailable helpers from `@cyanheads\u002Fmcp-ts-core\u002Ftesting\u002Ffuzz`: `fuzzTool`, `fuzzResource`, `fuzzPrompt`, `zodToArbitrary` (custom property-based tests), `adversarialArbitrary` and `ADVERSARIAL_STRINGS` (targeted injection sets). Returns a `FuzzReport` you can assert against. Options: `numRuns`, `numAdversarial`, `seed` (reproducibility), `timeout`, `ctx` (`MockContextOptions` for stateful handlers).\n\n## Generating Tests from Schemas\n\nWhen scaffolding tests for an existing handler, use the Zod schemas to generate meaningful test cases:\n\n1. **Read `input` schema** — identify required fields, optional fields with defaults, constrained types (enums, min\u002Fmax, patterns)\n2. **Read `output` schema** — know what shape to assert against\n3. **Happy path** — construct the simplest valid input, assert output matches schema\n4. **Defaults** — omit optional fields, verify defaults are applied in the output\n5. **Boundaries** — if the schema has `.min()`, `.max()`, `.length()`, test at the boundaries\n6. **Error paths** — trace the handler logic for throw conditions, construct inputs that trigger each\n7. **Sparse upstream fixtures** — if the handler\u002Fservice wraps a third-party API, add at least one fixture where upstream omits optional fields entirely. Assert that the output still validates and that `format()` renders uncertainty honestly (`Not available`, omitted badge, etc.) instead of fabricating values.\n\n## Checklist\n\n- [ ] Test file created in the repo's existing layout (`tests\u002F...` or colocated with source)\n- [ ] JSDoc `@fileoverview` and `@module` header present\n- [ ] Happy path tested with valid input → expected output\n- [ ] Error paths tested (at least one `.rejects.toThrow()`)\n- [ ] `format` function tested if defined\n- [ ] `createMockContext` options match handler's ctx usage (`tenantId`, `inputResponses`, `requestState`, `clientCapabilities`, `errors`, `signal`)\n- [ ] Service re-initialized in `beforeEach` if handler depends on a service singleton\n- [ ] If handler has optional fields: tested with empty-string inner values (form-client simulation)\n- [ ] If wrapping external API: sparse-payload case tested — fixture omits at least one optional upstream field; output still validates and `format()` renders uncertainty honestly instead of inventing values\n- [ ] If target is a prompt: `generate()` tested with valid args and (when applicable) no args\n- [ ] `bun run test` passes\n- [ ] `bun run devcheck` passes\n","## Context\n\nTests use Vitest and `createMockContext` from `@cyanheads\u002Fmcp-ts-core\u002Ftesting`. If the repo already has tests, match the existing layout. If the repo has no existing tests, create a root `tests\u002F` directory that mirrors the `src\u002F` structure (e.g. `tests\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002Fecho.tool.test.ts` for `src\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002Fecho.tool.ts`).\n\nFor the full `createMockContext` API and testing patterns, read:\n\n    framework-skills\u002Fapi-testing\u002FSKILL.md\n\n## Steps\n\n1. **Identify the target** — which tool, resource, or service needs tests\n2. **Read the source file** — understand the handler's logic, input\u002Foutput schemas, error paths, and which `ctx` features it uses\n3. **Create the test file** in the repo's existing test layout — search for existing `*.test.ts` files to confirm whether tests are colocated with source or under a root `tests\u002F` directory\n4. **Write test cases** covering happy path, error paths, and edge cases\n5. **Run `bun run test`** to verify\n6. **Run `bun run devcheck`** to verify lint, types, and MCP definitions\n\n## Determining What to Test\n\nRead the handler and identify:\n\n| Aspect | Test Strategy |\n|:-------|:-------------|\n| **Happy path** | Valid input → expected output. Include at least one. |\n| **Input variations** | Optional fields omitted, defaults applied, boundary values |\n| **Error paths** | Invalid state, missing resources, service failures → correct error thrown |\n| **`ctx.state` usage** | Available on any mock context (tenant `'default'` unless `{ tenantId }` says otherwise). It runs the production storage path, so use storage-legal keys (`cache\u002Fv1\u002Fabc`, never `cache:v1:abc`) and assert TTL expiry with fake timers. |\n| **`ctx.requestInput` \u002F `ctx.inputs`** | Two rounds. First round: assert the handler throws the input-required signal (`.rejects.toSatisfy(isInputRequiredSignal)`), or catch it and assert on `error.result.inputRequests`. Second round: seed `createMockContext({ inputResponses })` and assert the handler completes. Cover the decline\u002Fcancel branch too. A consent gate that redeems a `ctx.state` record also needs that record written into the second round's context, and a replay case showing the spent record asks again (see `api-testing` § Mock inputs). |\n| **`ctx.clientCapabilities`** | When the handler asks only if the client declared a capability, seed `createMockContext({ clientCapabilities })` with and without it and assert it asks in one case and falls through in the other. Seeding it also filters `inputResponses` to the declared kinds, as production does. |\n| **`ctx.signal`** | Pass `createMockContext({ signal: controller.signal })` and assert a long loop stops early rather than running to completion. |\n| **`ctx.fail` (typed contract)** | Definitions with `errors[]` need `fail` attached to the mock ctx — `createMockContext({ errors: myTool.errors })` does it for you. Assert on `data.reason` (stable per-contract entry), not just `code`. |\n| **`format` function** | Test separately if defined — it's pure, no ctx needed. Verify it renders the IDs and fields the model needs, not just a count or title. For projection-style tools, test non-default field selections. |\n| **Sparse upstream payloads** | For third-party API integrations, build a fixture with omitted fields. Assert normalized output still validates and `format()` preserves unknown values instead of inventing facts. |\n| **Form-client payloads** | If handler has optional fields: test with empty-string inner values (form clients send `\"\"` instead of `undefined`). Assert handler doesn't break or produce invalid output. |\n| **Auth scopes** | Not tested at handler level (framework enforces) — skip |\n\n## Templates\n\n### Tool test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{TOOL_NAME}} tool.\n * @module tests\u002Ftools\u002F{{TOOL_NAME}}.tool.test\n *\u002F\n\nimport { describe, expect, it } from 'vitest';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\nimport { {{TOOL_EXPORT}} } from '@\u002Fmcp-server\u002Ftools\u002Fdefinitions\u002F{{tool-name}}.tool.js';\n\ndescribe('{{TOOL_EXPORT}}', () => {\n  it('returns expected output for valid input', async () => {\n    const ctx = createMockContext();\n    const input = {{TOOL_EXPORT}}.input.parse({\n      \u002F\u002F valid input matching the Zod schema\n    });\n    const result = await {{TOOL_EXPORT}}.handler(input, ctx);\n    expect(result).toMatchObject({\n      \u002F\u002F expected output shape\n    });\n  });\n\n  it('throws on invalid state', async () => {\n    const ctx = createMockContext();\n    const input = {{TOOL_EXPORT}}.input.parse({\n      \u002F\u002F input that triggers an error path\n    });\n    await expect({{TOOL_EXPORT}}.handler(input, ctx)).rejects.toThrow();\n  });\n\n  \u002F\u002F Only when the tool declares `errors: [...]`. Drop this block otherwise.\n  it('throws ctx.fail(\"{{REASON}}\") for the declared failure mode', async () => {\n    const ctx = createMockContext({ errors: {{TOOL_EXPORT}}.errors });\n    const input = {{TOOL_EXPORT}}.input.parse({\n      \u002F\u002F input that triggers the declared failure mode\n    });\n    await expect({{TOOL_EXPORT}}.handler(input, ctx)).rejects.toMatchObject({\n      data: { reason: '{{REASON}}' },\n    });\n  });\n\n  it('formats output completely', () => {\n    const output = { \u002F* mock output matching the output schema *\u002F };\n    const blocks = {{TOOL_EXPORT}}.format!(output);\n    expect(blocks.some((block) => block.type === 'text')).toBe(true);\n    \u002F\u002F Assert the rendered text includes the IDs\u002Ffields the LLM needs to act on.\n  });\n});\n```\n\n### Resource test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{RESOURCE_NAME}} resource.\n * @module tests\u002Fresources\u002F{{RESOURCE_NAME}}.resource.test\n *\u002F\n\nimport { describe, expect, it } from 'vitest';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\nimport { {{RESOURCE_EXPORT}} } from '@\u002Fmcp-server\u002Fresources\u002Fdefinitions\u002F{{resource-name}}.resource.js';\n\ndescribe('{{RESOURCE_EXPORT}}', () => {\n  it('returns data for valid params', async () => {\n    const ctx = createMockContext({ tenantId: 'test-tenant' });\n    const params = {{RESOURCE_EXPORT}}.params.parse({\n      \u002F\u002F valid params matching the Zod schema\n    });\n    const result = await {{RESOURCE_EXPORT}}.handler(params, ctx);\n    expect(result).toBeDefined();\n  });\n\n  it('throws when resource not found', async () => {\n    const ctx = createMockContext({ tenantId: 'test-tenant' });\n    const params = {{RESOURCE_EXPORT}}.params.parse({\n      \u002F\u002F params for a non-existent resource\n    });\n    await expect({{RESOURCE_EXPORT}}.handler(params, ctx)).rejects.toThrow();\n  });\n\n  \u002F\u002F For resources that declare an `errors: [...]` contract, pass the contract via\n  \u002F\u002F `createMockContext` so the typed `ctx.fail` is wired automatically:\n  \u002F\u002F   const ctx = createMockContext({ errors: {{RESOURCE_EXPORT}}.errors });\n  \u002F\u002F   const err = await {{RESOURCE_EXPORT}}.handler(params, ctx).catch((e) => e);\n  \u002F\u002F   expect(err.code).toBe(JsonRpcErrorCode.NotFound);\n  \u002F\u002F   expect(err.data.reason).toBe('no_match');\n\n  \u002F\u002F Include this block only when the resource definition exports a `list` function.\n  \u002F\u002F Check the source — `list` is optional on resource definitions.\n  it('lists available resources', async () => {\n    const listing = await {{RESOURCE_EXPORT}}.list!();\n    expect(listing.resources).toBeInstanceOf(Array);\n    expect(listing.resources.length).toBeGreaterThan(0);\n    for (const r of listing.resources) {\n      expect(r).toHaveProperty('uri');\n      expect(r).toHaveProperty('name');\n    }\n  });\n});\n```\n\n### Service test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{SERVICE_NAME}} service.\n * @module tests\u002Fservices\u002F{{domain}}\u002F{{domain}}-service.test\n *\u002F\n\nimport { beforeEach, describe, expect, it } from 'vitest';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\nimport { StorageService } from '@cyanheads\u002Fmcp-ts-core\u002Fstorage';\nimport { get{{ServiceClass}}, init{{ServiceClass}} } from '@\u002Fservices\u002F{{domain}}\u002F{{domain}}-service.js';\n\n\u002F\u002F Derive the minimal mock config from src\u002Fconfig\u002Fserver-config.ts — read\n\u002F\u002F the server's Zod schema to see which fields init{{ServiceClass}}() needs.\nconst mockConfig = { \u002F* fields from server config schema *\u002F } as AppConfig;\n\ndescribe('{{ServiceClass}}', () => {\n  beforeEach(async () => {\n    const mockStorage = await StorageService.create({ type: 'in-memory' });\n    init{{ServiceClass}}(mockConfig, mockStorage);\n  });\n\n  it('performs the expected operation', async () => {\n    const ctx = createMockContext({ tenantId: 'test-tenant' });\n    const service = get{{ServiceClass}}();\n    const result = await service.doWork('input', ctx);\n    expect(result).toBeDefined();\n  });\n});\n```\n\nIf you need to test the accessor's \"not initialized\" guard, do it in a separate isolated-module test (`vi.resetModules()` before importing the service module). Don't mix that assertion into a suite that already calls `init{{ServiceClass}}()` in `beforeEach()`.\n\n### Multi-round-trip tool test\n\nA handler that calls `ctx.requestInput(...)` throws an `InputRequiredSignal` — in production the handler factory converts it to an `input_required` result; in a unit test it surfaces as a thrown value. Test both rounds.\n\n```typescript\nimport { isInputRequiredSignal } from '@cyanheads\u002Fmcp-ts-core';\nimport { createMockContext } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting';\n\nit('requests the missing input on the first round', async () => {\n  const ctx = createMockContext();\n  const input = {{TOOL_EXPORT}}.input.parse({ path: '\u002Ftmp\u002Fx' });\n\n  try {\n    await {{TOOL_EXPORT}}.handler(input, ctx);\n    throw new Error('Expected the handler to request input.');\n  } catch (error) {\n    if (!isInputRequiredSignal(error)) throw error;\n    expect(Object.keys(error.result.inputRequests ?? {})).toEqual(['confirm']);\n  }\n});\n\nit('completes once the response is supplied', async () => {\n  const ctx = createMockContext({\n    inputResponses: { confirm: { action: 'accept', content: { confirm: true } } },\n  });\n  const input = {{TOOL_EXPORT}}.input.parse({ path: '\u002Ftmp\u002Fx' });\n\n  await expect({{TOOL_EXPORT}}.handler(input, ctx)).resolves.toMatchObject({ deleted: '\u002Ftmp\u002Fx' });\n});\n\nit('does not re-ask after a decline', async () => {\n  const ctx = createMockContext({ inputResponses: { confirm: { action: 'decline' } } });\n  const input = {{TOOL_EXPORT}}.input.parse({ path: '\u002Ftmp\u002Fx' });\n\n  \u002F\u002F Terminal, not another round — re-asking would burn the round budget.\n  await expect({{TOOL_EXPORT}}.handler(input, ctx)).rejects.toThrow(McpError);\n});\n```\n\nFor a destructive consent gate, the second round completes only when the context holds the single-use record the first round stored, keyed by the `requestState` it returned — each mock context has its own `ctx.state`, so write the record into the second context before calling the handler. `api-testing` § Mock inputs has the full pattern, including the replay case.\n\n### Cancellation test\n\nPass an `AbortController` signal through `createMockContext` or `runToolContract`.\nAbort after a controlled I\u002FO operation or loop iteration starts, then assert that\nthe pending call settles and no further requests or iterations run. Use a deferred\nfixture or fake timers so the test does not depend on a wall-clock delay; restore\ntimers and close any fixture resources afterward. A defined result alone does not\nprove cancellation stopped the work.\n\nWhen an abort-aware handler throws after the signal fires, `runToolContract` returns\n`isError: true` with `structuredContent.error.code` equal to\n`JsonRpcErrorCode.RequestCancelled`; assert the cancellation message in `content[]`\nas well. Use schema-valid arguments: invalid arguments still return `InvalidParams`\nbefore the handler runs. A partial success is appropriate only when the tool's\ncontract explicitly supports it; assert its actual partial-result fields, output\nschema, and `format()` content instead of requiring every handler to return one.\n\n### Prompt test\n\n```typescript\n\u002F**\n * @fileoverview Tests for {{PROMPT_NAME}} prompt.\n * @module tests\u002Fprompts\u002F{{PROMPT_NAME}}.prompt.test\n *\u002F\n\nimport { describe, expect, it } from 'vitest';\nimport { {{PROMPT_EXPORT}} } from '@\u002Fmcp-server\u002Fprompts\u002Fdefinitions\u002F{{prompt-name}}.prompt.js';\n\ndescribe('{{PROMPT_EXPORT}}', () => {\n  it('generates valid messages for valid args', () => {\n    const args = {{PROMPT_EXPORT}}.args!.parse({\n      \u002F\u002F valid args matching the Zod schema\n    });\n    const messages = {{PROMPT_EXPORT}}.generate(args);\n    expect(messages).toBeInstanceOf(Array);\n    expect(messages.length).toBeGreaterThan(0);\n    for (const msg of messages) {\n      expect(msg).toHaveProperty('role');\n      expect(msg).toHaveProperty('content');\n    }\n  });\n\n  \u002F\u002F Include only when the prompt has no required args (args is optional or all fields optional).\n  it('generates messages with no args', () => {\n    const messages = {{PROMPT_EXPORT}}.generate({});\n    expect(messages.length).toBeGreaterThan(0);\n  });\n});\n```\n\n## Fuzz Testing\n\nFor schema-heavy or input-validation-critical handlers, the framework ships fuzz helpers that generate valid + adversarial inputs from your Zod schemas via `fast-check` and assert handler invariants (no crashes, no prototype pollution, no stack-trace leaks):\n\n```typescript\nimport { fuzzTool } from '@cyanheads\u002Fmcp-ts-core\u002Ftesting\u002Ffuzz';\n\nit('survives fuzz testing', async () => {\n  const report = await fuzzTool({{TOOL_EXPORT}}, { numRuns: 100 });\n  expect(report.crashes).toHaveLength(0);\n  expect(report.leaks).toHaveLength(0);\n  expect(report.prototypePollution).toBe(false);\n});\n```\n\nAvailable helpers from `@cyanheads\u002Fmcp-ts-core\u002Ftesting\u002Ffuzz`: `fuzzTool`, `fuzzResource`, `fuzzPrompt`, `zodToArbitrary` (custom property-based tests), `adversarialArbitrary` and `ADVERSARIAL_STRINGS` (targeted injection sets). Returns a `FuzzReport` you can assert against. Options: `numRuns`, `numAdversarial`, `seed` (reproducibility), `timeout`, `ctx` (`MockContextOptions` for stateful handlers).\n\n## Generating Tests from Schemas\n\nWhen scaffolding tests for an existing handler, use the Zod schemas to generate meaningful test cases:\n\n1. **Read `input` schema** — identify required fields, optional fields with defaults, constrained types (enums, min\u002Fmax, patterns)\n2. **Read `output` schema** — know what shape to assert against\n3. **Happy path** — construct the simplest valid input, assert output matches schema\n4. **Defaults** — omit optional fields, verify defaults are applied in the output\n5. **Boundaries** — if the schema has `.min()`, `.max()`, `.length()`, test at the boundaries\n6. **Error paths** — trace the handler logic for throw conditions, construct inputs that trigger each\n7. **Sparse upstream fixtures** — if the handler\u002Fservice wraps a third-party API, add at least one fixture where upstream omits optional fields entirely. Assert that the output still validates and that `format()` renders uncertainty honestly (`Not available`, omitted badge, etc.) instead of fabricating values.\n\n## Checklist\n\n- [ ] Test file created in the repo's existing layout (`tests\u002F...` or colocated with source)\n- [ ] JSDoc `@fileoverview` and `@module` header present\n- [ ] Happy path tested with valid input → expected output\n- [ ] Error paths tested (at least one `.rejects.toThrow()`)\n- [ ] `format` function tested if defined\n- [ ] `createMockContext` options match handler's ctx usage (`tenantId`, `inputResponses`, `requestState`, `clientCapabilities`, `errors`, `signal`)\n- [ ] Service re-initialized in `beforeEach` if handler depends on a service singleton\n- [ ] If handler has optional fields: tested with empty-string inner values (form-client simulation)\n- [ ] If wrapping external API: sparse-payload case tested — fixture omits at least one optional upstream field; output still validates and `format()` renders uncertainty honestly instead of inventing values\n- [ ] If target is a prompt: `generate()` tested with valid args and (when applicable) no args\n- [ ] `bun run test` passes\n- [ ] `bun run devcheck` passes\n",{"name":5,"metadata":43,"description":47},{"type":23,"author":44,"version":45,"audience":46},"cyanheads","1.9","external","Scaffold a test file for an existing tool, resource, or service. Use when the user asks to add tests, improve coverage, or when a definition exists without a matching test file.\n","main","3df1d0d67b30ff15236561f8c0f9f06d33f42dfd","skills\u002Fmcp-servers\u002Fcyanheads-add-test",17,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia","https:\u002F\u002Feth2030.com","Hardcore infra. Building @alt-research and applied cryptography.","2026-11-15 02:28:10",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add jiayaoqijia\u002Fcryptoskill --skill add-test",{"tool":63,"command":64},"bunx","bunx skills add jiayaoqijia\u002Fcryptoskill --skill add-test",{"tool":66,"command":67},"pnpm","pnpm dlx skills add jiayaoqijia\u002Fcryptoskill --skill add-test","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-add-test\u002FSKILL.md",true,[71,75,81],{"path":72,"resourceType":72,"resourceTypeDesc":73,"sizeBytes":74,"sourceHtmlUrl":16},"LICENSE","许可证",11317,{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"SOURCE.md","REFERENCE","参考文档",367,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-add-test\u002FSOURCE.md",{"path":82,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":83,"sourceHtmlUrl":84},"TRUST.auto.yaml",2217,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fcyanheads-add-test\u002FTRUST.auto.yaml",[86,96,104,112,120,128],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":91,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":95},"01M7DTKCERMV0RNX3HZJP4CZ26","troves","Deposit and withdraw from Troves DeFi yield vault strategies on Starknet. View available strategies, check positions, and manage vault deposits. Use this skill when the user mentions Troves, vault, yield vault, DeFi vault, strategy, yield farming, vault deposit, vault withdraw, earning yield through vaults, passive yield strategies, or wants to deposit into or withdraw from a yield strategy — even if they don't say \"Troves\" explicitly.","MIT","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":100,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":95},"01M7DTK6CJSMGC8KCQHGNYFZBD","trade","Swap tokens on Starknet via Fibrous DEX aggregator. Supports per-provider selection (avnu, ekubo, or auto to race all). Use this skill when the user wants to swap, exchange, trade, convert, buy, or sell one token for another on Starknet. Also use when the user asks about token prices, exchange rates, DEX routing, best swap route, or wants to check how much they would receive for a given amount — even if they don't explicitly say \"swap\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":108,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":95},"01M7DTJZ6A0X4PAW3Y8W4J9K64","staking","Stake, unstake, claim, and compound rewards for STRK, WBTC, tBTC, SolvBTC, and LBTC on Starknet. View validators, pools, and staking positions. Use this skill when the user mentions staking, delegating, validators, staking pools, rewards, compounding, unstaking, earning yield, passive income on crypto, or wants to earn on their STRK or BTC tokens — even if they don't say \"stake\" explicitly.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FSKILL.md",[],[],{"skillNo":113,"name":114,"nameZh":6,"description":115,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":116,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":95},"01M7DTJSDZJKCDMW7GHRF4BRH5","send","Send STRK, ETH, or any ERC-20 token to a Starknet address. Supports simulation (dry-run) before execution. Use this skill when the user wants to send, transfer, pay, tip, or move tokens to another wallet address on Starknet. Also trigger when the user mentions sending funds to someone, making a payment, transferring assets, or moving crypto to a specific address — even if they just say \"pay 10 STRK to 0x...\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":124,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":95},"01M7DTJG1E480D51ZQ7WKDQ26K","portfolio","View a comprehensive DeFi portfolio dashboard and optimize portfolio allocation via automated rebalancing. Use this skill when the user wants an overview, summary, dashboard, total value, net worth, portfolio rebalancing, target allocation, or wants to see all their DeFi positions across Starknet at once. Also trigger when the user asks \"what do I have\", \"show me everything\", \"how much am I worth\", \"my positions\", \"my investments\", \"rebalance my portfolio\", \"I want 50% ETH\", \"optimize my holdings\", or any request for a holistic view of their Starknet holdings — even if they don't explicitly say \"portfolio\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FSKILL.md",[],[],{"skillNo":129,"name":130,"nameZh":6,"description":131,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":90,"licenseFileUrl":132,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":95},"01M7DTJ7M8TE9R2N36HFBZDGVD","multi-swap","Execute multiple token swaps in a single Starknet transaction via Fibrous (default). Supports per-provider selection (avnu, ekubo, or auto to race all). Supports 2-3 swap pairs bundled into one multicall. Use this skill when the user wants to swap multiple token pairs at once, do batch swaps, execute several trades simultaneously, perform parallel swaps, or do bulk trading in one transaction. Also trigger when the user mentions \"two swaps\", \"three swaps\", \"swap X and Y at the same time\", or wants to convert multiple tokens in a single call.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FSKILL.md",[],[]]