Skip to content

Polaris Context MCP Prototype #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
7 changes: 7 additions & 0 deletions .prettierrc
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"arrowParens": "always",
"singleQuote": true,
"bracketSpacing": false,
"trailingComma": "all",
"quoteProps": "as-needed"
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"main": "dist/index.js",
"scripts": {
"build": "tsc && node -e \"require('fs').chmodSync('dist/index.js', '755')\"",
"build:watch": "tsc --watch",
"test": "vitest run",
"test:watch": "vitest",
"inspector": "npm run build && npm exec @modelcontextprotocol/inspector dist/index.js"
Expand Down
162 changes: 124 additions & 38 deletions src/tools/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { searchShopifyAdminSchema } from "./shopify-admin-schema.js";
import {McpServer} from '@modelcontextprotocol/sdk/server/mcp.js';
import {z} from 'zod';
import {searchShopifyAdminSchema} from './shopify-admin-schema.js';

const SHOPIFY_BASE_URL = "https://shopify.dev";
const SHOPIFY_BASE_URL = 'https://shopify-dev.myshopify.io/';

/**
* Searches Shopify documentation with the given query
Expand All @@ -12,23 +12,23 @@ const SHOPIFY_BASE_URL = "https://shopify.dev";
export async function searchShopifyDocs(prompt: string) {
try {
// Prepare the URL with query parameters
const url = new URL("/mcp/search", SHOPIFY_BASE_URL);
url.searchParams.append("query", prompt);
const url = new URL('/mcp/search', SHOPIFY_BASE_URL);
url.searchParams.append('query', prompt);

console.error(`[shopify-docs] Making GET request to: ${url.toString()}`);

// Make the GET request
const response = await fetch(url.toString(), {
method: "GET",
method: 'GET',
headers: {
Accept: "application/json",
"Cache-Control": "no-cache",
"X-Shopify-Surface": "mcp",
Accept: 'application/json',
'Cache-Control': 'no-cache',
'X-Shopify-Surface': 'mcp',
},
});

console.error(
`[shopify-docs] Response status: ${response.status} ${response.statusText}`
`[shopify-docs] Response status: ${response.status} ${response.statusText}`,
);

// Convert headers to object for logging
Expand All @@ -37,7 +37,7 @@ export async function searchShopifyDocs(prompt: string) {
headersObj[key] = value;
});
console.error(
`[shopify-docs] Response headers: ${JSON.stringify(headersObj)}`
`[shopify-docs] Response headers: ${JSON.stringify(headersObj)}`,
);

if (!response.ok) {
Expand All @@ -50,8 +50,8 @@ export async function searchShopifyDocs(prompt: string) {
console.error(
`[shopify-docs] Response text (truncated): ${
responseText.substring(0, 200) +
(responseText.length > 200 ? "..." : "")
}`
(responseText.length > 200 ? '...' : '')
}`,
);

// Parse and format the JSON for human readability
Expand All @@ -73,7 +73,7 @@ export async function searchShopifyDocs(prompt: string) {
}
} catch (error) {
console.error(
`[shopify-docs] Error searching Shopify documentation: ${error}`
`[shopify-docs] Error searching Shopify documentation: ${error}`,
);

return {
Expand All @@ -86,34 +86,63 @@ export async function searchShopifyDocs(prompt: string) {
}
}

async function fetchDocText(path: string): Promise<string> {
const appendedPath = path.endsWith('.txt') ? path : `${path}.txt`;
const url = new URL(appendedPath, SHOPIFY_BASE_URL);
const response = await fetch(url.toString());
return response.text();
}

export function shopifyTools(server: McpServer) {
server.tool(
"introspect_admin_schema",
'search_dev_docs',
`This tool will take in the user prompt, search shopify.dev, and return relevant documentation that will help answer the user's question.
It takes one argument: prompt, which is the search query for Shopify documentation.`,
{
prompt: z.string().describe('The search query for Shopify documentation'),
},
async ({prompt}, extra) => {
const result = await searchShopifyDocs(prompt);

return {
content: [
{
type: 'text' as const,
text: result.formattedText,
},
],
};
},
);

server.tool(
'introspect_admin_schema',
`This tool introspects and returns the portion of the Shopify Admin API GraphQL schema relevant to the user prompt. Only use this for the Shopify Admin API, and not any other APIs like the Shopify Storefront API or the Shopify Functions API.
It takes two arguments: query and filter. The query argument is the string search term to filter schema elements by name. The filter argument is an array of strings to filter results to show specific sections.`,
{
query: z
.string()
.describe(
"Search term to filter schema elements by name. Only pass simple terms like 'product', 'discountProduct', etc."
"Search term to filter schema elements by name. Only pass simple terms like 'product', 'discountProduct', etc.",
),
filter: z
.array(z.enum(["all", "types", "queries", "mutations"]))
.array(z.enum(['all', 'types', 'queries', 'mutations']))
.optional()
.default(["all"])
.default(['all'])
.describe(
"Filter results to show specific sections. Can include 'types', 'queries', 'mutations', or 'all' (default)"
"Filter results to show specific sections. Can include 'types', 'queries', 'mutations', or 'all' (default)",
),
},
async ({ query, filter }, extra) => {
const result = await searchShopifyAdminSchema(query, { filter });
async ({query, filter}, extra) => {
const result = await searchShopifyAdminSchema(query, {filter});

if (result.success) {
return {
content: [
{
type: "text" as const,
type: 'text' as const,
text: result.responseText,
},
],
Expand All @@ -122,34 +151,91 @@ export function shopifyTools(server: McpServer) {
return {
content: [
{
type: "text" as const,
type: 'text' as const,
text: `Error processing Shopify Admin GraphQL schema: ${result.error}. Make sure the schema file exists.`,
},
],
};
}
}
},
);

server.tool(
"search_dev_docs",
`This tool will take in the user prompt, search shopify.dev, and return relevant documentation that will help answer the user's question.
'read_docs',
`Use this tool for the same document retrieval as the read_doc tool, but
for multiple documents at once.
It takes one argument: prompt, which is the search query for Shopify documentation.`,
Args:
paths: The paths to the documents to read, in a comma separated list.
Paths should be relative to the root of the developer documentation site.`,
{
prompt: z.string().describe("The search query for Shopify documentation"),
paths: z.array(z.string()).describe('The paths to the documents to read'),
},
async ({ prompt }, extra) => {
const result = await searchShopifyDocs(prompt);
async ({paths}, extra) => {
const results = await Promise.all(
paths.map(async (path) => {
try {
const text = await fetchDocText(path);
return {path, text, success: true};
} catch (error) {
return {
path,
text: `Error fetching document at ${path}: ${error}`,
success: false,
};
}
}),
);

const formattedResults = results
.map((result) => {
return `## ${result.path}\n\n${result.text}\n\n`;
})
.join('---\n\n');

return {
content: [
{
type: "text" as const,
text: result.formattedText,
},
],
content: [{type: 'text' as const, text: formattedResults}],
};
}
},
);

server.tool(
'get_started',
`
READ THE FOLLOWING DOCUMENTATION BEFORE DOING A SINGLE THING!
- /docs/api/app-home/using-polaris-components.txt
- /docs/api/app-home.txt
- /docs/api/admin-extensions.txt
- /docs/api/customer-account-ui-extensions.txt
- /docs/api/checkout-ui-extensions.txt
Whenever the user asks about Polaris web components, shopify functions, or shopify graph ql always use this tool first to provide the most accurate and up-to-date documentation.
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

valid arguments for this tool are:
- "polaris-web-components"
- "polaris-web-components-admin-extensions"
- "polaris-web-components-checkout-extensions"
- "polaris-web-components-customer-account-extensions"
- "shopify-functions"
- "shopify-graphql"
Once you finish reading the documentation, you should then use the read_doc tool on the included paths to learn about more specific details. Overviews are not comprehensive, so this is important.
DON'T SEARCH THE WEB WHEN REFERENCING INFORMATION FROM THIS DOCUMENTATION. IT WILL NOT BE UP TO DATE. ONLY USE THE read_doc AND read_docs TOOLS TO RETRIEVE INFORMATION FROM THE DEVELOPER DOCUMENTATION SITE.
`,
{
surface: z
.string()
.optional()
.describe('The Shopify surface you are building for'),
},
async () => {
const docPath = `/docs/api/app-home/using-polaris-components`;
const text = await fetchDocText(docPath);

return {
content: [{type: 'text' as const, text}],
};
},
);
}