Implementar ferramentas, recursos e prompts
Crie os três primitivos para o caso de uso.
Implementar ferramentas, recursos e prompts é uma aula grátis de MCP Academy no CoddyKit. Esta é a aula 2 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.
Build All Three Primitives
With a plan in hand, you now write real code. This lesson wires up your tools, resources, and prompts into one working server. 🛠️
Set Up the Backend
First, give the server something to act on. A tiny store, like a list or a SQLite file, holds the notes every primitive will share.
import sqlite3
db = sqlite3.connect("notes.db")
db.execute("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY, title TEXT, body TEXT)")Write the Add Tool
Your first tool creates a note. The decorator publishes it, and the type hints turn the arguments into a schema the model can fill.
@mcp.tool()
def add_note(title: str, body: str) -> str:
db.execute("INSERT INTO notes(title, body) VALUES (?, ?)", (title, body))
db.commit()
return "Saved."Write the Search Tool
Add a second tool that searches notes by keyword. Returning a short list of matches keeps the result easy for the model to use.
@mcp.tool()
def search_notes(query: str) -> list[str]:
rows = db.execute("SELECT title FROM notes WHERE body LIKE ?", (f"%{query}%",))
return [r[0] for r in rows]Describe Tools Clearly
Give each tool a plain docstring. That text becomes its description, and a clear one helps the model pick the right tool at the right time.
Expose a Resource
Now serve read-only context. A resource uri lets the model fetch one note without changing anything in your store.
@mcp.resource("note://{note_id}")
def get_note(note_id: int) -> str:
row = db.execute("SELECT body FROM notes WHERE id = ?", (note_id,)).fetchone()
return row[0] if row else "Not found."Capture the URI Variable
The braces in the uri become a function argument. MCP pulls note_id straight from the path, so each read targets exactly one record.
Register a Prompt
Add a reusable prompt the user can trigger. It frames a request so callers get consistent, high-quality instructions every time.
@mcp.prompt()
def summarize(note_id: int) -> str:
return f"Read note://{note_id} and summarize it in three bullet points."Return Useful Text
Keep every result concise and human-readable. Short, clear strings save model tokens and make the user-facing output far easier to read.
Mix, But Keep Roles Clear
Tools act, resources read, and prompts instruct. Keeping each role distinct means clients and the model always know what to expect from each.
Wire the Entry Point
End the file by running the server so a client can connect. The run call starts the loop and hands control to the transport.
if __name__ == "__main__":
mcp.run()Quick Check
Let us check the resource uri detail.
Recap
You implemented all three primitives: tools that act, a resource that reads, and a prompt that instructs. The capstone server now does real work. 🎯
Perguntas Frequentes
A aula “Implementar ferramentas, recursos e prompts” é grátis?
Sim — o texto completo de “Implementar ferramentas, recursos e prompts” é 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 “Implementar ferramentas, recursos e prompts”?
Crie os três primitivos para o caso de uso. 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 2 de 4.
Quanto tempo leva a aula “Implementar ferramentas, recursos e prompts”?
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
- Definir o escopo do projeto e das ferramentas
- Implementar ferramentas, recursos e prompts
- Testar, inspecionar e reforçar a segurança
- Documentar e publicar o servidor