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 is the name of the hook. The second parameter is optional, and is covered in the Advanced Usage section.
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
Some hooks don’t need to access the agent’s context. You can declare them as static methods:
This hook will be handled without instantiating the agent.
Session-based Hooks
Sometimes you need a hook to be handled by a specific session. You can do this by utilizing the second parameter of the hook decorator:
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.