Using the Context object in Tools
mainTools can access an MCP Context object by including it as the last argument in the decorated method. The Context object provides capabilities for logging, progress reporting, and interacting with the server.
Available methods on Context include:
info(message: string): Log informational messages.debug(message: string): Log debug messages.error(message: string): Log error messages.reportProgress(current: number, total: number): Report progress to the client.readResource(uri: string): Read the content of a resource.
@Tool({ description: "A tool that uses context" })
async processData(dataSource: string, context: Context) {
context.info(`Starting to process data from ${dataSource}`);
try {
const data = await context.readResource(dataSource);
context.debug("Data loaded");
for (let i = 0; i < 5; i++) {
await new Promise((resolve) => setTimeout(resolve, 1000));
await context.reportProgress(i * 20, 100);
context.info(`Processing step ${i + 1} complete`);
}
return `Processed ${data.length} bytes of data from ${dataSource}`;
} catch (error) {
context.error(`Error processing data: ${(error as Error).message}`);
throw error;
}
}