Invocar ferramentas pelo código
Chame uma ferramenta do servidor e leia seu resultado.
Invocar ferramentas pelo código é uma aula grátis de MCP Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MCP Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MCP Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
From Listing to Doing
Discovery told you what exists. Now you actually invoke a tool, sending arguments and reading back the result from your own code.
Call by Name
Use session.call_tool() with the tool name and a dictionary of arguments. The names must match the inputSchema you discovered.
result = await session.call_tool(
"add",
{"a": 2, "b": 3},
)Arguments Must Validate
Your arguments dictionary should satisfy the tool inputSchema. Sending the wrong shape leads the server to reject the call.
await session.call_tool("greet", {"name": "Ada"})Read the Content
The result carries a content list of blocks. Most tools return text, so you read the text off the first block.
print(result.content[0].text)Check for Errors
A tool that fails sets isError to true on the result instead of raising. Inspect it so your client can react gracefully.
if result.isError:
print("tool failed")Structured Output Too
Newer tools may also return structuredContent, a typed object alongside the text, when the server defines an output schema.
print(result.structuredContent)Pass Real Arguments
Arguments come from your program, a user, or a model. The client simply forwards them as a plain dict to the named tool.
args = {"city": "Paris"}
await session.call_tool("weather", args)It Is Still Async
Like every network call, call_tool is awaited. The await pauses until the server finishes the work and the result returns.
One Call, One Result
Each invocation is a request-response pair. The session matches the reply to your request by id, so results never get crossed.
Handle Slow Tools
Some tools take time. A robust client sets a timeout so a hung tool does not freeze your whole program.
You Are the Orchestrator
Calling tools from code means your program decides the order, combines results, and turns raw output into something useful for the user.
Quick Check
How do you run a discovered tool from client code?
Recap: Making the Call
You invoked tools end to end: call by name with valid arguments, read the content blocks, and check isError before trusting the output.
Perguntas Frequentes
A aula “Invocar ferramentas pelo código” é grátis?
Sim — o texto completo de “Invocar ferramentas pelo código” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MCP Academy, atualize para CoddyKit PRO. O curso de MCP Academy inclui 4 aulas no total.
O que vou aprender em “Invocar ferramentas pelo código”?
Chame uma ferramenta do servidor e leia seu resultado. Você pratica MCP Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar MCP Academy?
Nenhuma experiência prévia é necessária. MCP Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Invocar ferramentas pelo código”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de MCP Academy?
Sim. Cada aula de MCP Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Abrir uma sessão de cliente
- Descobrir ferramentas e recursos
- Invocar ferramentas pelo código
- Encaminhar chamadas de ferramentas por um LLM