Build a coding assistant that can call tools in your own project. Start with a language-model response and add file operations, a tool loop, skills and language-server feedback. The workbook is free; a model provider may require its own account or usage charges.

Set up your project

Choose a starter for your language. C · C++ · C# · Go · Java · JavaScript · Python · Rust · TypeScript · Zig.

Use the examples in each stage to check your implementation locally. CodeCrafters operates its hosted runner separately.

Contents

Core project

1. Communicate with the LLM

Claude Code uses a REST API to communicate with the Large Language Model (LLM). In this stage, you’ll communicate with the provided LLM using an OpenAI-compatible API.

Original stage yy2

2. Advertise the read tool

In this stage, you’ll add support for advertising the Read tool in the request.

Tools

Tools are functions that an LLM can use to perform specific actions, like reading files or running commands.

By default, LLMs cannot access a user’s environment, such as their filesystem or terminal. To solve this, Claude Code provides several tools (like Read, Write, and Bash) that enable the model to read and modify the user’s codebase.

For this stage, you only need to advertise the Read tool (you’ll implement it in later stages).

Advertising Tools

Advertising tools lets the model know which tools are available and what arguments they accept.

To advertise tools, edit the existing request in the starter code to add a tools array:

 {
   "model": "...",
   "messages": [...],
+  "tools": [<tool1 spec>, <tool2 spec>, ...]
 }

For this stage, the tools array should include the Read tool’s specification:

{
  "type": "function",
  "function": {
    "name": "Read",
    "description": "Read and return the contents of a file",
    "parameters": {
      "type": "object",
      "properties": {
        "file_path": {
          "type": "string",
          "description": "The path to the file to read"
        }
      },
      "required": ["file_path"]
    }
  }
}

The structure consists of the following fields:

  • type: The type of tool (always "function" for tools)
  • function: Contains the function definition
    • name: The name of the function (e.g., “Read”)
    • description: Explains the function’s purpose and helps the LLM determine when to use it.
    • parameters: A JSON schema describing the function’s parameters
      • properties: Defines each parameter (in this case, just file_path)
      • required: Lists which parameters are mandatory
Tests

The tester will execute your program like this:

$ ./your_program.sh -p "How many tools are available to you in this request? Number only."
1

The tester will verify that:

  • Your program outputs a positive number
  • Your program exits with exit code 0
Notes
  • You can choose any reasonable name for the Read tool. The tester will only perform end-to-end tests by checking the LLM’s response. For example, any of the following names is valid:
    • Read
    • read
    • read_file
    • ReadFile, etc.
  • For this stage, you only need to advertise the Read tool’s availability in the request. We’ll handle tool calls in later stages.
  • See the OpenRouter API Specification for Tools for the full API documentation on how to include tools in your request.

Original stage aq1

3. Execute the read tool

In this stage, you’ll add support for detecting tool calls and executing the Read tool call.

Tool Calls

When the LLM decides to use a tool, the response message will contain a tool_calls array.

Here’s what the response looks like:

{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": {
              "name": "Read",
              "arguments": "{\"file_path\": \"/path/to/file.txt\"}"
            }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

The key fields you need to handle are:

  • choices: The list of generated responses. For this challenge, there will always be exactly one choice.
  • tool_calls: The array of tool calls to make
    • id: A unique identifier for the tool call
    • type: The type of tool call (always "function" for tools)
    • function: Contains the function details:
      • name: The name of the function to call (e.g., "Read")
      • arguments: A JSON string containing the function parameters

For this stage, you’ll execute a single Read tool call.

Executing the Read Tool

When you detect a tool_calls array in the response:

  1. Extract the tool call: Get the message from the first choice, then extract the first tool call from the tool_calls array.
  2. Parse the function name: Read the function name to determine which tool to execute.
  3. Parse the arguments: Parse the function arguments as a JSON string to get the parameters.
  4. Execute the tool: Your program must perform the action requested. For the Read tool, use your language’s file system library to read the file at the requested file_path.
  5. Output the result: Print the tool execution result. For the Read tool, print the raw file contents directly to stdout (just the contents, with no labels or formatting).

In previous stages, you printed the message content directly to stdout. Now that the model’s response can include tool calls, you should only print the message content if there’s no tool_calls array in the response.

Tests

The tester will create a file (e.g., apple.py) and execute your program like this:

$ ./your_program.sh -p "What is the content of apple.py? Print exact file contents without backticks."
<file contents>

The tester will verify that:

  • When the LLM requests a Read tool call, the output matches the exact file contents
  • When the LLM does not request a tool call, the output is the LLM’s text response
  • Your program exits with code 0
Notes
  • In later stages, you’ll send the tool results back to the model (instead of printing them) as part of the “agent loop” that drives Claude Code.
  • For this stage, you only need to print the result of the first tool call. We’ll get to handling multiple tool calls in later stages.
  • For a complete reference of the response structure, see the OpenRouter API Specification.

Original stage md6

4. Implement the agent loop

In this stage, you’ll implement an agent loop.

The Agent Loop

So far, your program handles a single interaction: send a prompt to the LLM, get a response, execute one tool if requested, and exit.

This works for simple tasks, but falls short when the task requires multiple steps (e.g., “read a file and fix any bugs”).

For this stage, you’ll implement an agent loop that repeatedly sends messages to the model and handles tool calls as needed, until the final result is received.

Here’s the structure in pseudocode:

messages = [{ role: "user", content: prompt }]

loop:
    response = call_api(messages)
    append response message to messages

    if response has no tool_calls:
        print response.content
        exit

    for each tool_call in response.tool_calls:
        result = execute_tool(tool_call)
        append {
            role: "tool",
            tool_call_id: tool_call.id,
            content: result
        } to messages

Let’s walk through each part of this loop:

  1. Initialize the conversation: You already have an initial conversation history: the messages array with the user’s prompt. Now you need to store this array so it can persist across iterations, since the loop will continuously append new messages to it:

    [
      { "role": "user", "content": "Summarize the README for me." }
    ]
  2. Enter the loop: Start the loop with the same API request you already have (sending your messages and tool specifications to the model). The difference is that this request now sits in a loop, allowing it to run multiple times.

  3. Record the assistant’s response: Whatever message the model returns, add it to your messages array. If the model wants to use a tool, the response will contain a tool_calls array:

    {
      "role": "assistant",
      "content": null,
      "tool_calls": [
        {
          "id": "call_abc123",
          "type": "function",
          "function": {
            "name": "Read",
            "arguments": "{\"file_path\": \"README.md\"}"
          }
        }
      ]
    }
  4. Execute tool calls: Check the model’s response to see if it’s requesting to use any tools. If tool calls are present:

    • a. Execute each requested tool (but do not print their result to stdout).
    • b. Add each tool call result to your messages array. Every tool result must:
      • Have the role field set to "tool"
      • Reference the corresponding tool_call_id
      • Include the tool call result as its content
    {
      "role": "tool",
      "tool_call_id": "call_abc123",
      "content": "# My Project\n\nChemical expiry period: 6 months"
    }
  5. Repeat until complete: Continue the loop until the model responds without requesting any tools (when tool_calls is missing or empty). At this point, print the final message content to stdout and exit.

Tests

The tester will create a Python project with:

  • README.md
  • Two Python files in app/ with randomized names

The tester will then execute your program like this:

$ ./your_program.sh -p "Use README.md to determine the chemical expiry period in months. Number only."
<expiry period in months>

The tester will verify that:

  • The output is the correct expiry period
  • Your program exits with exit code 0
Notes
  • Do not print raw file contents when executing the Read tool. This differs from the behavior in the “Execute the read tool” stage.
  • You can print intermediate debugging information to stderr. Print to stdout only when the final result is ready to be printed.
  • You can also use finish_reason: "stop" from the first response choice as a signal to stop the loop.

Original stage ff2

5. Implement the write tool

In this stage, you’ll add support for the Write tool.

The Write Tool

The Write tool enables the LLM to write content to files. Like with the Read tool, you need to advertise the Write tool in your request and execute it when the model requests it.

Here’s the tool specification:

{
  "type": "function",
  "function": {
    "name": "Write",
    "description": "Write content to a file",
    "parameters": {
      "type": "object",
      "required": ["file_path", "content"],
      "properties": {
        "file_path": {
          "type": "string",
          "description": "The path of the file to write to"
        },
        "content": {
          "type": "string",
          "description": "The content to write to the file"
        }
      }
    }
  }
}
Executing the Write Tool

When the model requests a Write tool call:

  1. Parse the arguments to extract the file_path and content
  2. Write the content to the file at the specified path:
    • If the file doesn’t exist, create it
    • If the file exists, overwrite it with the new content
  3. Append the result to messages as a tool message (just like with Read)
Tests

The tester will create the following files:

  • README.md with instructions
  • app/ directory for the project

The tester will then execute your program like this:

$ ./your_program.sh -p "Read README.md and create the required file. File should have 1 line. Reply with 'Created the file'"
Created the file

The tester will verify that:

  • The required file is created with the correct contents
  • Your program exits with exit code 0
Notes
  • You can choose any reasonable name for the Write tool (e.g., Write, write, write_file, WriteFile).

Original stage oz7

6. Implement the bash tool

In this stage, you’ll add support for the Bash tool.

The Bash Tool

The Bash tool enables the LLM to run shell commands. It gives the model direct access to the command line to perform actions like deleting files, creating directories, or running scripts.

You’ll need to advertise the Bash tool in your request and execute it when the model requests it.

Here is an example of the Bash tool’s specification:

{
  "type": "function",
  "function": {
    "name": "Bash",
    "description": "Execute a shell command",
    "parameters": {
      "type": "object",
      "required": ["command"],
      "properties": {
        "command": {
          "type": "string",
          "description": "The command to execute"
        }
      }
    }
  }
}
Executing the Bash Tool

When the model requests a Bash tool call:

  1. Parse the arguments to extract the command
  2. Execute the command using your language’s shell execution capabilities (e.g., subprocess.run() in Python, child_process.exec() in Node.js)
  3. Capture both stdout and stderr from the command
  4. Return the command output (or an error message if it failed) to the model as a tool message

For example, if the command is rm README_old.md, execute it and return the result (which will be empty if successful).

Tests

The tester will create three files:

  • app/main.js – Main project file
  • README.md – The current readme file
  • README_old.md – An old readme file

The tester will then execute your program like this:

$ ./your_program.sh -p "Delete the old readme file."
Deleted README_old.md

The tester will verify that:

  • README_old.md has been deleted (no longer exists)
  • app/main.js remains intact with its original contents
  • README.md remains intact with its original contents
  • Your program exits with code 0
Notes
  • You can choose any reasonable name for the Bash tool (e.g., Bash, bash, RunBashCommand, run_bash_command).
  • The result of the Bash tool call should be sent back to the model as part of the agent loop.
  • Make sure to execute the command in the same directory as your program, not in a temporary or different working directory.

Original stage oq5

Back to contents

Skills

1. Advertise skills to the LLM

In this stage, you’ll add support for finding skills on disk and advertising them to the LLM.

Skills

A skill is a folder of instructions that you can load into the model’s context on demand. Claude Code ships skills for things like reviewing pull requests or writing commit messages, and lets you add your own.

Skills live under .claude/skills/ in the project directory. Each skill is a folder containing a SKILL.md file:

.claude/
└── skills/
    ├── apple/
    │   └── SKILL.md
    └── grape/
        └── SKILL.md

A SKILL.md file has two parts: frontmatter (metadata between --- markers) and a body (everything after it):

---
name: apple
description: Deploys the apple service to production.
---

Run the deploy script and report the version that was deployed.

The frontmatter tells your program what a skill is for.

Progressive disclosure

The obvious way to tell the model about a skill is to paste its whole SKILL.md into the prompt. That doesn’t scale: ten skills of two hundred lines each would fill the context window before the user has asked anything.

Skills solve this with progressive disclosure. Claude loads only the front matter first, and loads the body and other dependencies when the skill is invoked. There are three levels (as given in the Agent Skills standard):

Level What gets loaded Rough size When
1 Name, description & other fields ~100 tokens per skill Always
2 The SKILL.md body Under 5,000 tokens When the skill is used
3 Bundled scripts and reference files Unbounded When the body points at them

For this stage, you’ll implement level 1 only.

Advertising skills

Lets walk through how a skill is advertised:

  1. Scan .claude/skills/, run through the skill folders and parse the frontmatter to read the name and description out of each SKILL.md, and add them to your system prompt. Do not include the bodies.

For example, if there are two skills: apple and grape, your system prompt will look like this.

You have access to the following skills:

- apple: Deploys the apple service to production.
- grape: Runs the grape test suite and reports failures.
  1. You already have an initial conversation history: the messages array with the user’s prompt. Add the system prompt at the front of the messages array.
 messages = [
+  { "role": "system", "content": "You have access to the following skills:\n\n- apple: ..." },
   { "role": "user", "content": prompt }
 ]
Tests

The tester will create a random number of skill folders, then describe a task taken from one skill’s description and ask which skill fits:

$ ./your_program.sh -p "Which skill would help me deploy the apple service? Respond with only the skill name."
apple
Notes
  • We recommend you implement a proper YAML parser at this stage. It’ll come in handy in later stages.
  • The Agent Skills standard requires the frontmatter name to match the folder name, so you can read either one, and later stages invoke skills by folder name.

Original stage vh1

2. Invoke a skill by name

In this stage, you’ll add support for invoking a skill by name.

Slash commands

The model knows every skill’s name and description, but it still can’t see any instructions. Loading a body is disclosure level 2, and the simplest trigger for it is the user asking directly.

When the user’s prompt starts with /, treat the first word as a skill name. Given this prompt:

$ ./your_program.sh -p "/apple"

your program should resolve apple to .claude/skills/apple/SKILL.md, read the body (everything after the closing ---), and send that body to the model instead of the raw prompt.

Resolving and loading

Given this skill file:

---
name: apple
description: Reports the deploy target for the apple service.
---

Respond with exactly one word: blueberry

Do not add any other text, punctuation, or formatting.

your messages array for /apple becomes:

[
  { "role": "system", "content": "You have access to the following skills:\n\n- apple: ..." },
  { "role": "user", "content": "Respond with exactly one word: blueberry\n\nDo not add any other text, punctuation, or formatting." }
]

Only the invoked skill’s body is loaded. The other skills stay at level 1: name and description only.

Tests

The tester will create two skills, each with a different word hidden in its body, and will invoke one of them:

$ ./your_program.sh -p "/apple"
blueberry

The tester will verify that:

  • Your program outputs the word from the invoked skill’s body
  • Your program exits with exit code 0
Notes
  • Load only the invoked skill’s body. If you load every body, the model will see two conflicting instructions and this stage will fail.
  • In addition to the folder name, Claude Code also handles additional cases, like plugins to resolve a command. We won’t deal with them in this extension.

Original stage jd8

3. Pass arguments to a skill

In this stage, you’ll add support for passing arguments to a skill.

Placeholders

A skill that always does the same thing isn’t much use. Real skills take input: deploy , review .

Skills accept input through placeholders in the body, which your program substitutes before sending the body to the model. There are two kinds:

Placeholder Replaced with
$ARGUMENTS Everything after the skill name, as one string
$ARGUMENTS[0], $ARGUMENTS[1], … A single argument, by zero-based position
$0, $1, $2, … Shorthand for sending single arguments

Both kinds can appear in the same body, and a placeholder can appear more than once.

Substituting

Given this invocation:

$ ./your_program.sh -p "/apple staging eu-west"

$ARGUMENTS becomes staging eu-west, $0 becomes staging, and $1 becomes eu-west.

So a body of:

Deploy to $0 in region $1. Full request was: $ARGUMENTS

is sent to the model as:

Deploy to staging in region eu-west. Full request was: staging eu-west

Arguments are split on whitespace. You don’t need to handle quoting.

Tests

The tester will create two skills and run your program twice.

The first skill’s body echoes $ARGUMENTS, and is invoked with a random number:

$ ./your_program.sh -p "/apple 4127"
4127

The second skill’s body echoes $1 followed by $0, so the two random words it’s invoked with come back in reverse order:

$ ./your_program.sh -p "/grape mango pear"
pear mango

The tester will verify that:

  • The $ARGUMENTS substitution reproduces the full argument string
  • The positional substitutions resolve to the right words, in the order the body asks for
Notes
  • Invoking a skill with no arguments should still work. Replace the placeholders with empty strings.
  • Claude Code supports several more substitutions, including named arguments and session variables. We won’t deal with them in this extension.

Original stage wd2

4. Stack multiple skills

In this stage, you’ll add support for stacking multiple skills in one prompt.

Stacking

So far a prompt has invoked one skill. Claude Code also lets you stack several at the start of one message:

$ ./your_program.sh -p "/apple /grape 4127"

When this is invoked, both the skill bodies of apple and grape are loaded, and the trailing text 4127 reaches each of them as $ARGUMENTS.

Where the names stop

Expansion runs from the start of the prompt. Every token that names a skill is expanded, and the first token that doesn’t ends the run. That token and everything after it become the argument text for every skill you expanded.

Prompt Expanded skills $ARGUMENTS for each expanded skill
/apple /grape 4127 apple, grape 4127
/apple 4127 /grape apple 4127 /grape
/apple /pear 4127 (no pear skill) apple /pear 4127

The last row assumes no skill named pear exists, so /pear ends expansion and stays in the argument text.

Building the messages

Given these two skills:

---
name: apple
description: Reports the deploy target for the apple service.
---

Add this exact line to your response: blueberry-$ARGUMENTS
---
name: grape
description: Summarizes recent incidents for the payments team.
---

Add this exact line to your response: cherry-$ARGUMENTS

your messages array for /apple /grape 4127 becomes:

[
  { "role": "system", "content": "You have access to the following skills:\n\n- apple: ..." },
  { "role": "user", "content": "Add this exact line to your response: blueberry-4127" },
  { "role": "user", "content": "Add this exact line to your response: cherry-4127" }
]

Each body is substituted separately, with the same argument text.

Tests

The tester will create three skills, each asking for a line built from a different random word, and will invoke two of them in one prompt with a random number as the shared argument:

$ ./your_program.sh -p "/apple /grape 4127"
blueberry-4127
cherry-4127

The third skill is seeded but never invoked.

The tester will verify that:

  • Both invoked skills’ lines appear in the output, each carrying the shared argument
  • The word belonging to the skill that wasn’t invoked is absent
Notes
  • Placeholder substitution works exactly as it did for a single skill. Each expanded body gets the same argument text.

Original stage sk5

5. Run a script bundled with a skill

In this stage, you’ll add support for skills that bundle an executable script.

Disclosure level 3

A skill folder can hold more than SKILL.md. The Agent Skills standard names three conventional subfolders:

  • scripts/ for executable code
  • references/ for documentation the model reads on demand
  • assets/ for templates and data.

All three are disclosure level 3: the model loads them only if the body tells it to. This stage covers scripts/.

This is what makes skills more than stored prompts. A body of two lines can point at a script of two hundred, and neither the script nor its output costs any context until it runs.

A skill with a bundled script looks like this:

.claude/
└── skills/
    └── apple/
        ├── SKILL.md
        ├── data.txt
        └── scripts/
            └── checksum.sh
Referencing a script

A skill shouldn’t have to hardcode its own location. It might be installed under the project, under the user’s home directory, or somewhere else entirely. So a body names its bundled files with paths relative to the skill’s own folder:

---
name: apple
description: Reports the checksum of the project data file.
---

Run `scripts/checksum.sh` using the Bash tool.

Respond with only the value it prints, and nothing else.

On its own that path leads nowhere: your program runs in the project root, and the script is at .claude/skills/apple/scripts/checksum.sh.

Your program already loads a skill’s body into messages when the user invokes it. The new work here is telling the model to read the path as relative to the skill’s folder. Naming that folder alongside the instructions is one way:

Skill: apple (located at .claude/skills/apple)
Paths in the instructions below are relative to that folder.

Run `scripts/checksum.sh` using the Bash tool.

Respond with only the value it prints, and nothing else.

So your messages array for /apple becomes:

[
  { "role": "system", "content": "You have access to the following skills:\n\n- apple: ..." },
  { "role": "user", "content": "Skill: apple (located at .claude/skills/apple)\nPaths in the instructions below are relative to that folder.\n\nRun `scripts/checksum.sh` using the Bash tool.\n\nRespond with only the value it prints, and nothing else." }
]

The model now has both halves: the folder from your message, and the relative path from the body. It joins them, calls the Bash tool you built in the base stages with .claude/skills/apple/scripts/checksum.sh, and your agent loop feeds the output back so it can report the value.

Tests

The tester will create a data file with random contents inside the skill’s folder.

$ cat .claude/skills/apple/scripts/checksum.sh
#!/usr/bin/env bash
cd "$(dirname "$0")/.." && sha256sum data.txt | cut -c1-8

It will then invoke the skill:

$ ./your_program.sh -p "/apple"
9f2b4c1a

The tester will verify that:

  • Your program outputs the eight-character checksum of the file the tester created
Notes
  • A project-relative folder like .claude/skills/apple is enough here, since the Bash tool runs from the project root.
  • Skills can also bundle references/ and assets/ next to scripts/, and a body names those the same way. We won’t deal with them in this extension.

Original stage tq1

6. Let the model choose a skill

In this stage, you’ll add support for the model choosing a skill on its own.

Model-invoked skills

Every skill so far has been triggered by the user typing /name. For this stage, your agent will decide when to invoke the skill.

The user describes a task in plain language, the model compares it against the descriptions already in its context, and loads the one that fits.

The descriptions are already there from earlier stages. What’s missing is a way for the model to ask for a body.

Giving the model a way in

The Skill tool enables the LLM to invoke a skill. Like with the Read, Write and Bash tools, you need to advertise the Skill tool in your request and execute it when the model requests it.

Here’s the tool specification:

{
    "type": "function",
    "function": {
      "name": "Skill",
      "description": "Load a skill's instructions into the conversation",
      "parameters": {
        "type": "object",
        "required": ["name"],
        "properties": {
          "name": { "type": "string", "description": "The name of the skill to use" },
          "args": { "type": "string", "description": "Optional arguments for the skill" }
        }
      }
    }
  }

After adding it to the list of tools, update the system prompt to point to this tool:

You have access to the following skills:

- apple: Use this skill when the user asks for the database migration status.
- grape: Use this skill when the user asks to format source code.

If a skill matches the user's request, call the Skill tool with its name
and follow the instructions it returns.

Your program looks the name up among the skills you discovered and returns that skill’s body as the tool result.

$ ./your_program.sh -p "What is the database migration status?"

The model matches the request against apple‘s description, calls Skill tool with "apple", and follows the body it gets back.

Notice what makes this work: the descriptions say when to use the skill, not just what it does. A description of “Database utilities” for the skill apple gives the model nothing to match against.

Tests

The tester will create two skills with clearly different descriptions, then send a request that matches exactly one of them without naming it:

$ ./your_program.sh -p "What is the database migration status?"
blueberry

The tester will verify that:

  • Your program outputs the word from the matching skill’s body
  • Your program exits with exit code 0
Notes
  • The second skill is a decoy. Its description won’t match the request, and its body contains a different word, so loading both skills will fail this stage.

Original stage gq2

7. Run a skill in a subagent

In this stage, you’ll add support for skills that run in a subagent.

Subagents

A skill can ask to be handled by a subagent instead of by the main agent you’ve been building, by setting context: fork in its frontmatter.

A subagent is a second run of your agent loop with a conversation of its own. It takes the skill’s body as its prompt, works through it, and hands back a single answer.

---
name: apple
description: Use this skill when the user asks about the on-call rotation.
context: fork
---

Respond with exactly one word: blueberry

By adding context:fork, apple’s body goes to the subagent. It has a new conversation stack and only the answer comes back to the main conversation.

What your program does

For ./your_program.sh -p "Who is on the on-call rotation right now?":

  1. Discover the skills and build the catalog for the system prompt, as before.
  2. The model matches the question against apple and calls the Skill tool, the same way it did in previous stages.
  3. Check context before returning the body. apple asks for a subagent, so its body doesn’t go into the main conversation. Start a separate list of messages holding only that body, and run your agent loop over it.
  4. Return the subagent’s answer as the tool’s result. For the above skill, that result can be:
 Skill apple ran in a separate context and returned: blueberry
  1. Run your agent loop over the main conversation, and print its answer.

Steps 3 and 4 happen inside the Skill tool handler you wrote in previous stages. Until now it returned a body for every name it recognised, and a forked skill is the one case where it returns something else.

Steps 3 and 5 are the same loop. A subagent is that loop called again with a different list of messages, so most of this stage is pulling the loop out of wherever it currently lives.

The subagent’s messages

The subagent’s conversation starts empty. It receives the skill’s body and nothing else, so the question that triggered it never reaches it:

[
  { "role": "user", "content": "Respond with exactly one word: blueberry" }
]

Say it answers blueberry. That word is the only thing that comes out of the subagent. Whatever your program wraps around that word on the way back, as step 4 does, is your own framing rather than something the subagent returned.

Tests

The tester will create two skills with random names, one of them asking for a subagent, and ask a question that matches it. Its body asks for a random word:

$ ./your_program.sh -p "Who is on the on-call rotation right now?"
The on-call engineer is blueberry.

The other skill is seeded but never matched, so the catalog holds more than the skill under test.

The tester will watch the requests your program sends, and verify that:

  • One of them carries the skill’s instructions without the question that triggered them
  • The subagent’s answer appears in your program’s output
Notes
  • A skill that asks for a subagent ends a stacking run, so it’s never expanded alongside another.
  • Claude Code also supports an agent field that picks which type of subagent handles the skill. We won’t be handling different subagent types in this extension.

Original stage mj2

Back to contents

Language Server Protocol

1. Add the LSP tool

In this stage, you’ll make the LSP tool available to the model.

Why LSP?

Searching for a function name can find unrelated functions or miss uses through an alias. A language server analyzes a project’s code to connect those uses to their definitions. The Language Server Protocol (LSP) lets your agent ask that server where a symbol is defined, just as an editor does.

Expected behavior

The supplied client connects to the language server started by the tester. Your agent must initialize the client before its first model request and keep the connection available throughout the run. When connected, every model request must advertise the LSP tool below. When unconfigured, the agent continues with its existing tools.

For now, an LSP call receives a placeholder such as LSP is not implemented yet as a tool result with the matching tool_call_id. The agent then continues its conversation with the model. Definition lookup comes in the next stage.

{
  "type": "function",
  "function": {
    "name": "LSP",
    "description": "Returns the file, line, and character where a symbol is defined.",
    "parameters": {
      "type": "object",
      "properties": {
        "operation": {
          "type": "string",
          "enum": ["goToDefinition"]
        },
        "filePath": {
          "type": "string",
          "description": "Absolute path, or a path relative to the agent's current working directory."
        },
        "line": {
          "type": "integer",
          "minimum": 1,
          "description": "1-based line number of the symbol."
        },
        "character": {
          "type": "integer",
          "minimum": 1,
          "description": "1-based character offset in UTF-16 code units (same as character count for ASCII)."
        }
      },
      "required": ["operation", "filePath", "line", "character"]
    }
  }
}

The arguments point at a spot in a file rather than a name, because total alone could mean the one in pricing.py, discounts.py, or preview.py. For example, to point at invoice_total in checkout.py‘s return statement, the model sends line 5, character 12. Both count from 1, as in an editor:

{
  "operation": "goToDefinition",
  "filePath": "checkout.py",
  "line": 5,
  "character": 12
}

The model should understand that the tool finds definitions and that its inputs are one-based. The tool description or your system prompt can provide this information.

Supplied client

The client handles the server connection and fetches its configuration during initialization. Its API for your language is:

For C

The supplied client is lsp_client.h, at src/lsp_client.h. Its initialization call is lsp_from_environment(&lsp). 1 means connected, 0 unconfigured, and -1 an initialization error.

For C++

The supplied client is lsp_client.hpp, at src/lsp_client.hpp. Its initialization call is LSPClient::from_environment(). It returns an optional client, with std::nullopt when unconfigured.

For C#

The supplied client is LSPClient.cs, at src/LSPClient.cs. Its initialization call is await LSPClient.FromEnvironmentAsync(). It returns a client, or null when unconfigured.

For Go

The supplied client is lsp_client.go, at app/lsp_client.go. Its initialization call is LSPClientFromEnvironment(). It returns a client and an error; the client is nil when unconfigured.

For Java

The supplied client is LSPClient.java, at src/main/java/LSPClient.java. Its initialization call is LSPClient.fromEnvironment(). It returns a client, or null when unconfigured. Initialization can throw checked exceptions.

For JavaScript

The supplied client is lsp_client.js, at app/lsp_client.js. Its initialization call is await LSPClient.fromEnvironment(). It returns a client, or null when unconfigured.

For Python

The supplied client is lsp_client.py, at app/lsp_client.py. Its initialization call is LSPClient.from_environment(). It returns a client, or None when unconfigured.

For Rust

The supplied client is lsp_client.rs, at src/lsp_client.rs. Its initialization call is LspClient::from_environment(). It returns a Result holding an optional client, with None when unconfigured.

For TypeScript

The supplied client is lsp_client.ts, at app/lsp_client.ts. Its initialization call is await LSPClient.fromEnvironment(). It returns a client, or null when unconfigured.

For Zig

The supplied client is lsp_client.zig, at src/lsp_client.zig. Its initialization call is LSPClient.fromEnvironment(allocator, io, init.environ_map). It returns an error union holding an optional client, with null when unconfigured.

Tests

The tester will create the invoice project and execute your program like this:

$ ./your_program.sh -p "Use LSP goToDefinition on checkout.py at line 5, character 12. If navigation is not implemented yet, report the tool response without retrying."
LSP client connected
<the model's report of the tool response>

The tester will verify that:

  • Your program connects the supplied LSP client before its first model request
  • Every model request advertises the LSP tool, with operation, filePath, line, and character required
  • The model’s goToDefinition call gets a tool result, with the matching tool_call_id
  • Your program exits with code 0
Notes

For C

  • lsp_from_environment initializes an LSPClient value. Release it with lsp_deinit when the agent is finished with the connection.

For Zig

  • Release the client with deinit when the agent is finished with the connection.

  • LSP client connected is a startup log on standard error. Standard output is reserved for the model’s answer.

  • Only goToDefinition is offered for now. Reference lookup and a handler that contacts the language server come in later stages.

  • The supplied project is Python regardless of the language you use to implement your agent.

  • For more background, see the LSP specification and Claude Code’s LSP tool.

Original stage iy3

2. Find the implementation

In this stage, you’ll implement goToDefinition, which tells the model where a function is defined.

Why look up a definition?

A call may use an imported alias rather than the function’s original name. In the invoice project, invoice_total in checkout.py calls pricing.total. Definition lookup follows that relationship so the model can use Read to inspect the right implementation.

Expected tool result

For a goToDefinition call on checkout.py at line 5, character 12, the tool result must identify pricing.py at line 1, character 5. Return a path relative to the agent’s working directory and a one-based position, for example:

Defined in pricing.py:1:5

The result must reach the model through the existing tool-result flow with the matching tool_call_id. The agent continues its conversation, allowing the model to retrieve the implementation with Read.

Opening source documents

Before a file’s first lookup, the language server needs its contents in a textDocument/didOpen notification. The server remembers the document for the connection; a second didOpen for the same URI is rejected.

LSP identifies documents by absolute file URIs. Resolve relative paths against the agent’s working directory and encode special characters: /project/cart notes.py becomes file:///project/cart%20notes.py. A document’s initial version is 1. Its languageId comes from the client’s configured extension-to-language mapping; .py maps to python in this project.

A notification payload looks like this:

{
  "method": "textDocument/didOpen",
  "params": {
    "textDocument": {
      "uri": "file:///project/checkout.py",
      "languageId": "python",
      "version": 1,
      "text": "<complete contents of checkout.py>"
    }
  }
}

A notification tells the server something without expecting an LSP reply. The client sends it with the notify action. The server must receive didOpen before the definition request, and a failed notification doesn’t mark the file as open.

Definition requests and positions

The model’s goToDefinition call corresponds to a textDocument/definition request, sent through the client’s request action. It uses the same URI as didOpen, but positions count from zero:

Position Line Character
Model’s tool input 5 12
Language-server request 4 11

Both interfaces count columns in UTF-16 code units.

{
  "method": "textDocument/definition",
  "params": {
    "textDocument": { "uri": "file:///project/checkout.py" },
    "position": { "line": 4, "character": 11 }
  }
}

For this lookup, the server returns:

{
  "uri": "file:///project/pricing.py",
  "range": {
    "start": { "line": 0, "character": 4 },
    "end": { "line": 0, "character": 9 }
  }
}

The range covers the name total in its definition, starting at the t and ending just after the name. Its start position, 0:4, becomes the one-based 1:5 in your tool result.

Supplied client API

The client’s call method takes an action (notify or request) and a payload. Read its definition in your supplied lsp_client file for the exact argument and return types. The language mapping is exposed as extension_to_language, extensionToLanguage, or ExtensionToLanguage, depending on your language. Include the dot when looking up an extension, such as .py.

Tests

The tester will create the invoice project and execute your program like this:

$ ./your_program.sh -p "Use LSP goToDefinition on checkout.py at line 5, character 12. Read the returned implementation and explain which total is called; preview.total is unrelated."
<the model's explanation that checkout calls pricing.total>

The tester will verify that:

  • Your program sends textDocument/didOpen for checkout.py, then textDocument/definition at position 4:11
  • The tool result for that call names pricing.py at line 1, character 5, with the matching tool_call_id
  • Read returns the complete contents of pricing.py to the model
  • Your program exits with code 0
Notes
  • The LSP tool’s path argument is filePath, not file_path as in Read.
  • Await asynchronous client calls so the opening notification completes before the request.
  • A definition lookup can also return several locations, no location, or a server error. We won’t deal with those in this extension.
  • The protocol defines positions, document opening, and definition requests.

Original stage gz6

3. Find the affected callers

In this stage, you’ll implement findReferences to find the callers affected by an API change.

Why find references?

Changing a function’s return type can break callers in other files. In the invoice project, checkout imports pricing.total as invoice_total, while reporting calls it by its original name. Reference lookup finds uses tied to that definition, including aliases, while excluding the unrelated preview.total and comments that merely mention the name.

Expected tool result

Each location returned by the server must reach the model with its relative file path and one-based start line and character. Several locations in one file remain separate references. For the full invoice project, a result can look like this:

Found 6 references across 3 files:

pricing.py:
  Line 1:5

checkout.py:
  Line 1:21
  Line 5:12

reports.py:
  Line 1:21
  Line 5:12
  Line 5:28

Return the result with the matching tool_call_id. When the server returns an empty array, report that no references were found, for example No references found.

Tool interface

The LSP tool must advertise both goToDefinition and findReferences. Both operations identify a symbol with filePath, line, and character, using the same one-based input positions. The model should understand that it can use the tool to find definitions and references.

Ask where the function is used

The model starts at the definition of pricing.total:

{
  "operation": "findReferences",
  "filePath": "pricing.py",
  "line": 1,
  "character": 5
}

Line 1, character 5 points to the t in def total. This tells the server which function’s references to find, rather than asking it to match every occurrence of the word total.

The queried file must be open before the request, following the URI and position rules from definition lookup. Opening checkout.py in an earlier lookup doesn’t open pricing.py.

The corresponding textDocument/references request uses the zero-based position 0:4 and the client’s request action:

{
  "method": "textDocument/references",
  "params": {
    "textDocument": { "uri": "file:///project/pricing.py" },
    "position": { "line": 0, "character": 4 },
    "context": { "includeDeclaration": true }
  }
}

Its context.includeDeclaration setting asks the server to include the symbol’s own declaration along with its uses. This stage requires includeDeclaration to be true.

Understanding reference locations

The server returns an array of file URIs and zero-based ranges. For example, these two locations identify separate calls in reports.py:

[
  {
    "uri": "file:///project/reports.py",
    "range": {
      "start": {"line": 4, "character": 11},
      "end": {"line": 4, "character": 16}
    }
  },
  {
    "uri": "file:///project/reports.py",
    "range": {
      "start": {"line": 4, "character": 27},
      "end": {"line": 4, "character": 32}
    }
  }
]

The full result also includes imports, the declaration in pricing.py, and uses in checkout.py. Reference locations can describe any of these; each must remain represented in the tool result.

Tests

The tester will create the invoice project and execute your program like this:

$ ./your_program.sh -p "Use LSP findReferences on pricing.py at line 1, character 5, and list the callers that a change to pricing.total's return type would affect. Don't change any code. Preserve the returned locations; preview.total and comments are unrelated."
<the model's list of the affected callers>

The tester will verify that:

  • Your program sends textDocument/references for pricing.py at position 0:4, with includeDeclaration set to true
  • The tool result names every location the server returned, each with its file and 1-based line and character, with the matching tool_call_id
  • Your program exits with code 0

The tester will also run this prompt against a server that returns an empty array.

Notes
  • See the references request specification for the protocol details.
  • Other language servers can represent aliased references differently. Pyright, for example, returns checkout’s import of total but not the invoice_total call. Return whatever the server finds, and the model can read checkout.py to follow the alias to the call.

Original stage rb6

4. Keep the analysis current

In this stage, you’ll synchronize Write edits so definition and reference lookups use the updated code.

Why synchronize edits?

After the model changes checkout’s import from pricing to discounts, a lookup on invoice_total should find discounts.total. Saving the file updates the disk, but the language server still holds the text sent with didOpen. Synchronizing Write edits keeps its answers consistent with the saved code.

Expected behavior

Every successful Write to a supported file must synchronize the complete saved text before returning its tool result. Subsequent definition and reference lookups must reflect the edits. The client’s language mapping identifies supported files (.py maps to python in the invoice project).

The notification depends on the document’s state on the current connection:

Document state Notification Version
Already open through navigation or Write textDocument/didChange Previous version plus one
Not yet open textDocument/didOpen, including its mapped language ID 1

Navigation and Write must agree on the URI, open state, and current version of each document throughout the run. The save must succeed before the notification, and the recorded version advances only after that notification succeeds.

Full document updates

For example, if checkout.py is open at version 1, changing its import to discounts sends this didChange notification:

{
  "method": "textDocument/didChange",
  "params": {
    "textDocument": { "uri": "file:///project/checkout.py", "version": 2 },
    "contentChanges": [{ "text": "from discounts import total as invoice_total\n\n\ndef checkout_total() -> int:\n    return invoice_total(250, 2)\n" }]
  }
}

The server uses full synchronization: contentChanges contains one object with the complete text that was saved, including line breaks. No diff or edit range is needed.

The version tells the server which copy is newest, so each change must use a higher number than the last. The next Write to checkout.py sends version 3.

The model should use Write for edits so they reach the language server.

Tests

The tester will create the invoice project and execute your program like this:

$ ./your_program.sh -p "Use LSP goToDefinition on checkout.py at line 5, character 12. Use Write to change its import from pricing to discounts, preserving the invoice_total alias. Repeat definition lookup at the same position and report the new target. Restore the pricing import using Write and repeat the definition lookup."
<the model's report of the three definition targets>

The tester will verify that:

  • The three lookups’ tool results point to pricing.py, then discounts.py, then pricing.py again
  • Each Write sends checkout.py with a higher version than the last
  • checkout.py on disk ends with the pricing import
  • The server’s copy of every open document matches the file on disk
  • Your program exits with code 0

The tester will also run a prompt that writes checkout.py before any lookup, so the Write has to send didOpen.

Notes
  • Read and returned reference locations don’t open documents in the language server. A Write to an indexed but closed file still needs didOpen with the new contents.
  • JavaScript, TypeScript, and C# clients are asynchronous; await the notification before returning Write’s result.
  • The protocol defines the didChange notification.
  • Every test case uses a successful Write to a supported Python file. We won’t deal with failed writes or files outside the language mapping in this extension.

Original stage bn2

5. Repair edits with diagnostics

In this stage, you’ll report language-server diagnostics to the model so it can repair an API migration.

Why diagnostics?

A change to one file can break a caller in another. A language-server diagnostic describes the issue with a message, severity, and source range. Passing new reports to the model lets it find and repair these mistakes, including problems in files it hasn’t edited.

Expected feedback

Before each model request, any newly available, current diagnostics must reach the model through the latest tool result. Each diagnostic needs its relative file path, message, and one-based start line and character. For example:

<new-diagnostics>The following new diagnostic issues were detected:

checkout.py:
  [Line 5:12] Type Price is not assignable to return type int</new-diagnostics>

The wording and grouping can differ. Write keeps its existing success result; diagnostics arrive as additional feedback on a later turn. Reports for any file count, including files that the last Write didn’t change.

Current and new reports

Only textDocument/publishDiagnostics notifications carry diagnostic reports. Their version determines whether the contents are current:

Report Required behavior
Version matches the last version sent for that file Accept the report
Version differs from the last version sent for that file Ignore the report
No version supplied Accept the report

The latest current report replaces the previous report for that file. An empty diagnostics array clears its earlier issues. Only issues absent from those last shown for that file should be appended to a tool result. Unchanged issues must not be repeated on every turn.

Feedback during a migration

The tester asks the model to migrate the invoice project using your agent’s tools. The required behavior is:

Function Before migration After migration
pricing.total(250, 2) Integer 500 A Price TypedDict with an integer cents field: {"cents": 500}
checkout_total() Integer 500 Integer 500
report_total() Integer 600 Integer 600

Tests and the unrelated preview.total must stay unchanged. The model chooses its edits and uses your agent’s diagnostic feedback to repair any type errors.

For example, changing pricing.total can make this unchanged caller invalid:

def checkout_total() -> int:
    return invoice_total(250, 2)

It now returns a Price where its annotation promises an int. The language server can report that mismatch in checkout.py even when the last edit was to pricing.py. That report must reach the model so it can repair the caller.

Read the server’s reports

The server sends diagnostics asynchronously in textDocument/publishDiagnostics notifications. They are not the response to didChange. Your LSP client queues them while your agent executes other calls.

The client’s notifications action reads this queue using a cursor, starting at 0:

{ "after": 0, "timeoutMs": 0 }

after identifies the notifications already read. The response contains newer notifications and a new cursor for the next call. timeoutMs: 0 reads queued messages without waiting for analysis to finish. After the pricing.py write above, a response can contain:

{
  "cursor": 4,
  "notifications": [
    {
      "method": "textDocument/publishDiagnostics",
      "params": {
        "uri": "file:///project/checkout.py",
        "version": 1,
        "diagnostics": [
          {
            "range": {
              "start": { "line": 4, "character": 11 },
              "end": { "line": 4, "character": 32 }
            },
            "severity": 1,
            "message": "Type Price is not assignable to return type int"
          }
        ]
      }
    }
  ]
}

Every returned cursor applies to the next queue read, even when the batch is empty or contains only unrelated notifications. Diagnostic ranges count from zero, like the locations the server returns for navigation. Convert their start positions to one-based coordinates for the model.

The model should understand that new diagnostics are feedback to use when repairing its edits.

Tests

The tester will create the invoice project with test_invoice.py and execute your program like this:

$ ./your_program.sh -p "Change pricing.total to return a Price TypedDict with an integer cents field. Update checkout.py and reports.py so their results stay unchanged. Before any Write edits, use LSP goToDefinition on checkout.py at line 5, character 12, and LSP findReferences on the returned pricing.total definition. After all Write edits, repeat LSP findReferences at the updated pricing.total definition. That query is required even if the project tests pass. Fix the type errors your tools report. Leave tests and unrelated files unchanged. Run python3 -m unittest -v test_invoice.py and report the result."
<the model's summary of the migration and the test result>

The tester will verify that:

  • Every current diagnostic the server published, for any file, reaches the model with its file, message, and 1-based line and character
  • No diagnostic from a report for an older version reaches the model
  • Both lookups run, in either order, before the first Write
  • A references lookup runs after the last Write, and its result matches the edited files
  • The Bash output shows Ran 5 tests and OK, checkout_total() returns 500, and report_total() returns 600
  • preview.py and test_invoice.py are unchanged
  • Your program exits with code 0

The tester will also run this prompt against a server that sends stale reports and current reports without a version. Its pricing.py has a comment line above def total, so the definition is not on line 1.

Notes
  • Await asynchronous notifications calls before sending the next model request.
  • Write’s own result stays as it was. Diagnostics reach the model through a later tool result instead.
  • A report can arrive after the model request that followed its change. Your agent reads it before the next request.
  • The model chooses its own edits, so a run may or may not hit a type error. You don’t need to introduce errors yourself.

Original stage ql9

Back to contents

Source and licence

Stage material by CodeCrafters. Source snapshot · Original licence.

MIT License

Copyright (c) 2022 CodeCrafters

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.