Hooks
Add HTTP endpoints to your Magma agents
Overview
Hooks in Magma allow you to expose HTTP endpoints that external services can call to interact with your agent. They’re perfect for handling webhooks, callbacks, and API integrations.
Implementation
To add a hook to your agent, use the @hook
decorator:
The first parameter of the decorator is the name of the hook. The second parameter is optional, and is covered in the Advanced Usage section.
The function being decorated should take in an express Request and Response, which you can access directly to read and write data.
Hook URLs
When your agent is deployed, hooks are automatically exposed at:
Request Handling
Hooks support both GET and POST methods by default. The request and response objects are the standard Express Request and Response type, giving you access to:
req.query
- URL query parametersreq.body
- POST request bodyreq.headers
- HTTP headersreq.params
- URL parameters
You can also use the res
object to send a response to the caller.
res.status(code).json(body)
- Send a JSON responseres.send(body)
- Send a string or buffer responseres.end()
- End the response
For more information on the Express Request and Response objects, see the Express documentation.
Common Use Cases
OAuth Callbacks
Webhook Listeners
API Endpoints
Best Practices
- Validation: Always validate incoming data
- Error Handling: Implement proper error handling
- Security: Implement authentication when needed
Hooks are publicly accessible endpoints. Always implement appropriate security measures for sensitive operations.
Advanced Usage
Static Hooks
If you don’t need a hook to access any agent state, you can define it as a static hook.
Session Routing for Hooks
If you are unfamiliar with sessions, you should first review the concept of Sessions.
You can direct the hook to a specific session id using the session argument of the second parameter of the decorator. This argument is an optionally async function that takes in the request, and returns the session id.
This will direct the hook to the session with the id that matches the userId
in the request body.
To learn more about sessions, see the Sessions page.
Limitations
- File uploads are limited to 10MB
- Webhook timeout is 30 seconds
- Rate limiting applies based on your plan
For long-running operations, consider using a job instead of a hook, or implement an async pattern with a status endpoint.