How an MCP tool actually works (part 3)
This is the third part in a short series on AI in Laravel, where I’m digging under the hood of MCP tools and looking at what the model is really doing when it decides to use one.
In the last post, I wrote an MCP tool by hand for Scout, and looked at what the model reads when it decides to use a tool. What I hadn’t really looked at yet is what happens around the tool… the back-and-forth between my code and the model, where the model asks for a tool, my code runs it, and the result goes back to the model. That’s often called the agent loop.
So this time, I wanted to build that loop myself, by hand, and then rebuild the same thing with Laravel’s AI SDK (laravel/ai), to see what the SDK is doing for me.
Building the loop by hand
First, I built AgentLoop, a CLI command that takes in a question as a string argument, which might look like this:
php artisan app:agent-loop "What is an MCP?"
Then, the handler constructs an array of available tools (i.e. functions) that it could leverage, and presents them, along with the question, to a model (e.g. Claude), which decides which tool to use. With that decision, our handler calls that function, and gives the response back to the model. This is all done in a loop until it gets the answer it needs, and then it returns its own answer to us from that.
In my example, my agent could reach for a single function (findNote) that would just return some info about two different topics, MCP and REST, in the form of an array with two keyed items.
Here’s what the manual loop itself looks like:
while ($turn < $maxTurns) {
$turn++;
$response = Http::withHeaders([
'x-api-key' => config('services.anthropic.key'),
'anthropic-version' => '2023-06-01',
])->post('https://api.anthropic.com/v1/messages', [
'model' => 'claude-haiku-5-5',
'max_tokens' => 1024,
'tools' => $tools,
'messages' => $messages,
]);
$reply = $response->json();
// ...check for errors, track the cost, log the step...
$messages[] = [
'role' => 'assistant',
'content' => $reply['content'],
];
if ($reply['stop_reason'] === 'end_turn') {
$text = collect($reply['content'])->firstWhere('type', 'text');
// print to the terminal
$this->info("Final answer: {$text['text']}");
return;
}
// ...run each tool the model asked for, and send the results back...
}
One thing that caught me out was that the model can ask for more than one tool at once. When I asked it to compare my MCP and REST notes, it asked for both notes in the same reply. My first version only answered the first one, and the API rejected the next request. So the handler loops over every tool the model asked for, and sends a result back for each one:
$toolResults = [];
foreach (collect($reply['content'])->where('type', 'tool_use') as $toolCall) {
$toolName = $toolCall['name'];
$arguments = $toolCall['input'];
$result = "Unknown tool: {$toolName}";
if ($toolName === 'find_note') {
$result = $this->findNote($arguments['title']);
}
$toolResults[] = [
'type' => 'tool_result',
'tool_use_id' => $toolCall['id'],
'content' => $result,
];
}
$messages[] = [
'role' => 'user',
'content' => $toolResults,
];
Each result carries the tool_use_id from the request it answers, so the model knows which result belongs to which tool call.
I also added a few guards while I was in there. There’s a turn cap ($maxTurns), so the loop can’t go on forever, and a cost cap ($maxCost), which works out the cost of each turn from the tokens the model reports back. There’s also a step log, which writes each turn to a file so I can see what happened afterwards.
Rebuilding it with Laravel’s AI SDK
Then, I built AgentSdk, an implementation of the same CLI ability, but using Laravel’s AI SDK to do the grunt work of the looping and middleware before we get our response. The CLI command takes the same question and passes it off to the NotesAgent class, which has a similar list of tools it could call to handle it. In this case, the tools() function returns an array (like our first version), with a single instance of FindNote, and a middleware() method handles the token spend limit and logging the steps. The FindNote handler itself gets called, to look up the note, so the model can write its answer from it.
The CLI command now comes down to one line that runs the agent:
$response = (new NotesAgent)->prompt($question);
$this->info("Final answer: {$response}");
$this->line("Steps: " . count($response->steps));
$this->line("Input tokens: {$response->usage->inputTokens}");
$this->line("Output tokens: {$response->usage->outputTokens}");
The agent sets which provider and model to use, and the turn cap, with attributes:
#[Provider(Lab::Anthropic)]
#[Model('claude-haiku-5-5')]
#[MaxSteps(5)]
class NotesAgent implements Agent, Conversational, HasTools, HasMiddleware
{
use Promptable;
public function tools(): iterable
{
return [
new FindNote,
];
}
public function middleware(): array
{
return [
Stop::unless(function (PendingStep $step) {
$cost = ($step->usage->inputTokens * 0.10
+ $step->usage->outputTokens * 0.50) / 1_000_000;
return $cost < 0.01;
}),
new LogSteps,
];
}
}
Middleware here is a small class that runs once before each step of the loop, similar to Laravel’s HTTP middleware. The SDK ships a Stop middleware, which I used for the cost cap, and I wrote LogSteps myself for the step log.
What the SDK was hiding
What the SDK version abstracts away is the looping until the model gets the answers it needs, keeping track of the token counting, and any HTTP requests to the model, as well as error handling. It also matches each tool result back to the tool call it belongs to, including when the model asks for several tools at once.
Some things were still mine to write, though. The SDK counts tokens, but it doesn’t know what they cost, so the dollar math in the cost cap is still my code. When the cost cap stopped a run, the SDK didn’t tell me why… the final answer just came back empty. I think it’s a good idea to know why a model run gets stopped.
Where MCP fits in
The tool in both versions is plain PHP - a function that we own. As with the MCP tool in part 1, the model only sees its name, description, and schema. So the loop is the same either way… MCP is one way of plugging tools into it, from a separate server, instead of defining them in your own app.
This is the third part of a short series I’m writing on AI in Laravel. If you’d like each part in your inbox, along with a few things that don’t make it to the blog, sign up for the AI for Laravel series below.
Join my Email List
I write about how AI tools like MCP actually work, and practical AI for developers. I'll email you when a new part of the series is out.