@marcelo-ochoa/server-postgres 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/db.js CHANGED
@@ -61,6 +61,9 @@ export async function initializePool(connectionString) {
61
61
  const url = new URL(`postgresql://${database}`);
62
62
  resourceBaseUrl = url;
63
63
  }
64
+ export function isPoolInitialized() {
65
+ return pool !== undefined;
66
+ }
64
67
  export function getPool() {
65
68
  if (!pool) {
66
69
  throw new Error("Postgres connection pool not initialized. Use pg-connect tool first.");
package/dist/handlers.js CHANGED
@@ -1,9 +1,9 @@
1
- import { withConnection } from "./db.js";
2
1
  import { queryHandler } from "./tools/query.js";
3
2
  import { statsHandler } from "./tools/stats.js";
4
3
  import { connectHandler } from "./tools/connect.js";
5
4
  import { explainHandler } from "./tools/explain.js";
6
5
  import { awrHandler } from "./tools/awr.js";
6
+ export { listResourcesHandler, readResourceHandler } from "./resources.js";
7
7
  const toolHandlers = {
8
8
  "pg-query": queryHandler,
9
9
  "pg-stats": statsHandler,
@@ -18,72 +18,3 @@ export const callToolHandler = async (request) => {
18
18
  }
19
19
  throw new Error(`Unknown tool: ${request.params.name}`);
20
20
  };
21
- const SCHEMA_PATH = "schema";
22
- export const listResourcesHandler = async (request) => {
23
- return await withConnection(async (client) => {
24
- const result = await client.query("SELECT table_name, table_schema FROM information_schema.tables WHERE table_schema NOT IN ('information_schema', 'pg_catalog')");
25
- return {
26
- resources: result.rows.map((row) => ({
27
- uri: `postgres://${row.table_schema}/${row.table_name}/${SCHEMA_PATH}`,
28
- mimeType: "application/json",
29
- name: `"${row.table_schema}"."${row.table_name}" database schema`,
30
- })),
31
- };
32
- });
33
- };
34
- export const readResourceHandler = async (request) => {
35
- const resourceUrl = new URL(request.params.uri);
36
- const pathComponents = resourceUrl.pathname.split("/");
37
- const schema = pathComponents.pop();
38
- const tableName = pathComponents.pop();
39
- const schemaName = resourceUrl.hostname;
40
- if (schema !== SCHEMA_PATH) {
41
- throw new Error("Invalid resource URI");
42
- }
43
- return await withConnection(async (client) => {
44
- const columnsResult = await client.query(`SELECT
45
- column_name,
46
- data_type,
47
- is_nullable,
48
- column_default,
49
- character_maximum_length,
50
- numeric_precision,
51
- numeric_scale
52
- FROM information_schema.columns
53
- WHERE table_name = $1 AND table_schema = $2
54
- ORDER BY ordinal_position`, [tableName, schemaName]);
55
- const indexesResult = await client.query(`SELECT
56
- ix.relname as index_name,
57
- i.indisunique as is_unique,
58
- a.attname as column_name
59
- FROM
60
- pg_class t,
61
- pg_class ix,
62
- pg_index i,
63
- pg_attribute a,
64
- pg_namespace n
65
- WHERE
66
- t.oid = i.indrelid
67
- AND ix.oid = i.indexrelid
68
- AND a.attrelid = t.oid
69
- AND a.attnum = ANY(i.indkey)
70
- AND t.relkind = 'r'
71
- AND t.relname = $1
72
- AND n.oid = t.relnamespace
73
- AND n.nspname = $2
74
- ORDER BY
75
- ix.relname`, [tableName, schemaName]);
76
- return {
77
- contents: [
78
- {
79
- uri: request.params.uri,
80
- mimeType: "application/json",
81
- text: JSON.stringify({
82
- columns: columnsResult.rows,
83
- indexes: indexesResult.rows
84
- }, null, 2),
85
- },
86
- ],
87
- };
88
- });
89
- };
@@ -0,0 +1,73 @@
1
+ import { withConnection, isPoolInitialized } from "./db.js";
2
+ const SCHEMA_PATH = "schema";
3
+ export const listResourcesHandler = async (request) => {
4
+ if (!isPoolInitialized()) {
5
+ return { resources: [] };
6
+ }
7
+ return await withConnection(async (client) => {
8
+ const result = await client.query("SELECT table_name, table_schema FROM information_schema.tables WHERE table_schema NOT IN ('information_schema', 'pg_catalog')");
9
+ return {
10
+ resources: result.rows.map((row) => ({
11
+ uri: `postgres://${row.table_schema}/${row.table_name}/${SCHEMA_PATH}`,
12
+ mimeType: "application/json",
13
+ name: `"${row.table_schema}"."${row.table_name}" database schema`,
14
+ })),
15
+ };
16
+ });
17
+ };
18
+ export const readResourceHandler = async (request) => {
19
+ const resourceUrl = new URL(request.params.uri);
20
+ const pathComponents = resourceUrl.pathname.split("/");
21
+ const schema = pathComponents.pop();
22
+ const tableName = pathComponents.pop();
23
+ const schemaName = resourceUrl.hostname;
24
+ if (schema !== SCHEMA_PATH) {
25
+ throw new Error("Invalid resource URI");
26
+ }
27
+ return await withConnection(async (client) => {
28
+ const columnsResult = await client.query(`SELECT
29
+ column_name,
30
+ data_type,
31
+ is_nullable,
32
+ column_default,
33
+ character_maximum_length,
34
+ numeric_precision,
35
+ numeric_scale
36
+ FROM information_schema.columns
37
+ WHERE table_name = $1 AND table_schema = $2
38
+ ORDER BY ordinal_position`, [tableName, schemaName]);
39
+ const indexesResult = await client.query(`SELECT
40
+ ix.relname as index_name,
41
+ i.indisunique as is_unique,
42
+ a.attname as column_name
43
+ FROM
44
+ pg_class t,
45
+ pg_class ix,
46
+ pg_index i,
47
+ pg_attribute a,
48
+ pg_namespace n
49
+ WHERE
50
+ t.oid = i.indrelid
51
+ AND ix.oid = i.indexrelid
52
+ AND a.attrelid = t.oid
53
+ AND a.attnum = ANY(i.indkey)
54
+ AND t.relkind = 'r'
55
+ AND t.relname = $1
56
+ AND n.oid = t.relnamespace
57
+ AND n.nspname = $2
58
+ ORDER BY
59
+ ix.relname`, [tableName, schemaName]);
60
+ return {
61
+ contents: [
62
+ {
63
+ uri: request.params.uri,
64
+ mimeType: "application/json",
65
+ text: JSON.stringify({
66
+ columns: columnsResult.rows,
67
+ indexes: indexesResult.rows
68
+ }, null, 2),
69
+ },
70
+ ],
71
+ };
72
+ });
73
+ };
package/dist/server.js CHANGED
@@ -1,19 +1,13 @@
1
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
1
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
- import { CallToolRequestSchema, ListResourcesRequestSchema, ListResourceTemplatesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
4
3
  import { z } from "zod";
5
4
  import { initializePool } from "./db.js";
6
5
  import { listResourcesHandler, readResourceHandler, callToolHandler } from "./handlers.js";
7
6
  import { tools } from "./tools.js";
8
- const server = new Server({
7
+ // Create server instance
8
+ const server = new McpServer({
9
9
  name: "postgres-server",
10
- version: "1.0.6",
11
- }, {
12
- capabilities: {
13
- resources: {},
14
- tools: {},
15
- prompts: {}, // Add this line to indicate support for prompts
16
- },
10
+ version: "1.0.8",
17
11
  });
18
12
  const prompts = [
19
13
  { name: "pg-query: Execute Query", description: "pg-query select * from test" },
@@ -22,30 +16,58 @@ const prompts = [
22
16
  { name: "pg-connect: Database Connection", description: "pg-connect to PostgreSQL using a connection string like host.docker.internal:5432/dbname with user name and password" },
23
17
  { name: "pg-awr: Performance Report", description: "pg-awr to generate a PostgreSQL performance report (requires pg_stat_statements extension)" }
24
18
  ];
25
- const PromptsListRequestSchema = z.object({
26
- method: z.literal("prompts/list"),
27
- params: z.object({}),
19
+ // Register Prompts
20
+ server.registerPrompt("postgres-prompts", {
21
+ description: "List available Postgres prompts"
22
+ }, async () => ({
23
+ messages: [
24
+ {
25
+ role: "assistant",
26
+ content: {
27
+ type: "text",
28
+ text: "Available Postgres prompts:\n" + prompts.map(p => `- ${p.name}: ${p.description}`).join("\n")
29
+ }
30
+ }
31
+ ]
32
+ }));
33
+ // Register Resource Templates
34
+ const resourceTemplate = new ResourceTemplate("postgres://{schema}/{table}/schema", {
35
+ list: async () => listResourcesHandler({})
28
36
  });
29
- server.setRequestHandler(PromptsListRequestSchema, async () => {
30
- return {
31
- prompts,
32
- };
37
+ server.registerResource("Table Schema", resourceTemplate, { description: "Schema information for a PostgreSQL database table including column names and data types" }, async (uri) => {
38
+ return readResourceHandler({ params: { uri: uri.toString() } });
33
39
  });
34
- server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {
35
- return {
36
- resourceTemplates: [
37
- {
38
- uriTemplate: "postgres://{schema}/{table_name}/schema",
39
- name: "Table Schema",
40
- description: "Schema information for a PostgreSQL database table including column names and data types",
41
- },
42
- ],
43
- };
40
+ // Register Tools
41
+ tools.forEach(tool => {
42
+ // Basic mapping of JSON schema to Zod for simple cases
43
+ let inputSchema = z.object({});
44
+ if (tool.inputSchema && tool.inputSchema.properties) {
45
+ const shape = {};
46
+ for (const [key, prop] of Object.entries(tool.inputSchema.properties)) {
47
+ let field = z.any();
48
+ if (prop.type === "string") {
49
+ field = z.string();
50
+ }
51
+ if (prop.description) {
52
+ field = field.describe(prop.description);
53
+ }
54
+ if (tool.inputSchema.required && !tool.inputSchema.required.includes(key)) {
55
+ field = field.optional();
56
+ }
57
+ else if (!tool.inputSchema.required) {
58
+ field = field.optional();
59
+ }
60
+ shape[key] = field;
61
+ }
62
+ inputSchema = z.object(shape);
63
+ }
64
+ server.registerTool(tool.name, {
65
+ description: tool.description,
66
+ inputSchema: inputSchema
67
+ }, async (args) => {
68
+ return callToolHandler({ params: { name: tool.name, arguments: args } });
69
+ });
44
70
  });
45
- server.setRequestHandler(ListResourcesRequestSchema, listResourcesHandler);
46
- server.setRequestHandler(ReadResourceRequestSchema, readResourceHandler);
47
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
48
- server.setRequestHandler(CallToolRequestSchema, callToolHandler);
49
71
  export async function runServer() {
50
72
  const args = process.argv.slice(2);
51
73
  const databaseUrl = args[0];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@marcelo-ochoa/server-postgres",
3
3
  "mcpName": "io.github.marcelo-ochoa/postgres",
4
- "version": "1.0.6",
4
+ "version": "1.0.8",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/marcelo-ochoa/servers.git",