Using MCP Integrations
Multi-provider Context (MCP) integrations allow your Mastra application to interact with external services, APIs, or custom logic hosted elsewhere. These integrations are defined using the <tool>
element within your <datamodel>
.
Once defined, MCP tools bridge the gap between your application's data model and its dynamic components:
- For
<script>
elements: Exposed methods of the tool become directly callable. - For
<llm>
elements: The tool's capabilities can be made available to the language model.
This allows you to encapsulate complex external interactions and make them easily accessible within your application flow.
Integration with LLM Elements
For LLM elements, MCP tools can be added by referencing the tool ID in the tools
prop. This allows the LLM to invoke the capabilities provided by the external service.
Integration with Script Elements
For script elements, MCP tools are available through the ctx.tools
object within the script's execution context. You can access a specific tool using its ID as the key (e.g., ctx.tools['weather']
) and call its exposed methods.
Common Patterns
-
API Integration: Using a tool to fetch data from an external API and store it in the datamodel.
-
LLM with Multiple Tools: Providing an LLM with access to several tools for more complex tasks.
Advanced Usage
Conditional Tool Loading for LLMs
You can dynamically determine which tools are available to an LLM based on the application state or user preferences.
Error Handling in Scripts
When calling tool methods within scripts, implement standard error handling to manage potential issues with the external service.