import { ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { DatabaseManager } from '../database/manager.js';
import { logger } from '../utils/logger.js';
import { z } from 'zod';
export async function handleReadResource(request: z.infer<typeof ReadResourceRequestSchema>) {
try {
const db = DatabaseManager.getInstance();
const uri = request.params.uri;
if (uri.startsWith('mysql://database/')) {
// Return database information
const dbName = uri.replace('mysql://database/', '');
const tables = await db.getTables(dbName);
return {
contents: [
{
uri,
mimeType: 'application/json',
text: JSON.stringify({
database: dbName,
tables: tables
}, null, 2)
}
]
};
} else if (uri.startsWith('mysql://table/')) {
// Return table information
const tablePath = uri.replace('mysql://table/', '');
const pathParts = tablePath.split('/');
let tableName: string;
let database: string | undefined;
if (pathParts.length === 2) {
// Multi-DB mode: database/table
database = pathParts[0];
tableName = pathParts[1];
} else {
// Single-DB mode: just table
tableName = pathParts[0];
}
const tableInfo = await db.getTableInfo(tableName, database);
return {
contents: [
{
uri,
mimeType: 'application/json',
text: JSON.stringify(tableInfo, null, 2)
}
]
};
} else {
throw new Error(`Unknown resource URI: ${uri}`);
}
} catch (error) {
logger.error('Failed to read resource', { error, uri: request.params.uri });
throw new Error(`Failed to read resource: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}