Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ Official [Model Context Protocol](https://modelcontextprotocol.io) server for th
| ----------------------- | ------------------------------------------------------------ |
| `list_sites` | List all sites in your account for a given data partition |
| `get_site` | Get details of a specific site |
| `create_site` | Create a new site |
| `create_site` | Create a new site, or a redirect host |
| `delete_site` | Delete a site |
| `list_domains` | List available domains (shared and custom) |
| `get_account` | Get account info, subscription plan, and usage |
Expand All @@ -44,6 +44,8 @@ Official [Model Context Protocol](https://modelcontextprotocol.io) server for th

Redirects apply only on your organization's own custom domains. User rules, kept on the hostname and changed through these tools, are checked before the live deploy's `_redirects`.

To forward a hostname with no content of its own, such as a retired domain or a campaign link, create a redirect host: `create_site` with `kind: "redirect"`, then add its rules. A redirect host serves only its rules and takes no deploys. It doesn't count toward your plan's site limit; an organization can have up to 50.

## Usage

Authentication is via OAuth 2.0. Static access tokens are not supported.
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
},
"dependencies": {
"@hono/node-server": "^1.13.0",
"@hostsmith/sdk": "^1.5.0",
"@hostsmith/sdk": "^1.6.0",
"@modelcontextprotocol/sdk": "^1.12.1",
"hono": "^4.6.0",
"zod": "^3.24.0"
Expand Down
23 changes: 17 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ Plans and limits:
- Every plan, Free included, can create sites in both the "us" and the "eu" partition. Pass partition: "eu" when the user asks for the EU or GDPR; otherwise omit it, and the site goes to the user's home partition.
- When a plan's site limit is reached, creating a site returns the API error "Site limit reached for current plan". Surface it verbatim so the user knows they need to delete a site or upgrade.

Redirect hosts:
- To forward a hostname with no content of its own, such as a retired domain or a campaign link, create a redirect host (create_site with kind: "redirect") and set its rules with set_redirects or add_redirect, rather than deploying a placeholder page.

Deploying content:
- Two paths, pick by file size and type:
- Use deploy_files for inline text/JSON/HTML you generated yourself, when total payload < ~1 MB. Bytes ship through the MCP server's JSON-RPC channel; subject to a ~6 MB hard ceiling.
Expand Down Expand Up @@ -176,7 +179,7 @@ export function buildServer(): McpServer {

server.tool(
"list_sites",
'List Hostsmith sites in the user\'s account. Returns each site\'s `siteId`, `subdomain`, `domain`, and current status - feed `siteId` into `get_site`, `deploy_files`, `deploy_create_upload`, or `delete_site`. This is the source of truth for "does the user already have a site at FQDN X" - call it before any create/deploy/delete to resolve the user\'s site reference. By default queries all data partitions and merges the results; pass `partition: "us"` or `"eu"` to limit the query.',
'List Hostsmith sites in the user\'s account. Returns each site\'s `siteId`, `subdomain`, `domain`, `kind` (`"redirect"` for a redirect host, which takes no deploys) and current status - feed `siteId` into `get_site`, `deploy_files`, `deploy_create_upload`, or `delete_site`. This is the source of truth for "does the user already have a site at FQDN X" - call it before any create/deploy/delete to resolve the user\'s site reference. By default queries all data partitions and merges the results; pass `partition: "us"` or `"eu"` to limit the query.',
{
partition: partitionSchema
.optional()
Expand Down Expand Up @@ -327,7 +330,9 @@ export function buildServer(): McpServer {

\`domain\` MUST be one of the domains returned by \`list_domains\` for this user - never invent or assume one. The selected domain must be in \`active\` status; if it isn't, surface the problem to the user instead of attempting creation. \`partition\` passed to this tool MUST match the partition of the selected domain.

Subdomain selection must respect the domain's capabilities from \`list_domains\`. To serve the bare apex, pass \`subdomain: "www"\` - only valid when the domain has \`enableApexDomain: true\` (typically custom domains the user owns). For any other subdomain, the domain must have \`enableSubdomains: true\`; shared hosting domains (e.g. \`*.hostsmith.link\`) and most custom domains have \`enableApexDomain: false\`, so a non-apex subdomain is required there. If the chosen domain doesn't support the kind of site the user asked for (apex vs subdomain), surface the conflict rather than silently picking something else.`,
Subdomain selection must respect the domain's capabilities from \`list_domains\`. To serve the bare apex, pass \`subdomain: "www"\` - only valid when the domain has \`enableApexDomain: true\` (typically custom domains the user owns). For any other subdomain, the domain must have \`enableSubdomains: true\`; shared hosting domains (e.g. \`*.hostsmith.link\`) and most custom domains have \`enableApexDomain: false\`, so a non-apex subdomain is required there. If the chosen domain doesn't support the kind of site the user asked for (apex vs subdomain), surface the conflict rather than silently picking something else.

Pass \`kind: "redirect"\` to create a redirect host instead of a site: it serves only redirect rules, set afterwards with \`set_redirects\` or \`add_redirect\`, and takes no deploys. Its domain must be a custom domain the organization owns (\`shared: false\` in \`list_domains\`). On a domain with \`enableApexDomain: true\`, a redirect host at \`subdomain: "www"\` also forwards the bare apex, which first redirects to \`www\` and then follows the host's rules.`,
{
domain: z
.string()
Expand All @@ -349,12 +354,18 @@ Subdomain selection must respect the domain's capabilities from \`list_domains\`
.describe(
"Data partition for the new site. Must match the partition of the selected domain.",
),
kind: z
.enum(["site", "redirect"])
.optional()
.describe(
'Omit, or pass "site", for a site that serves deployed files. Pass "redirect" for a redirect host: it serves only redirect rules, needs a custom domain the organization owns, and doesn\'t count toward the plan\'s site limit (up to 50 per organization). Fixed at creation.',
),
},
{ title: "Create site", destructiveHint: true },
async ({ domain, subdomain, partition }, extra) => {
async ({ domain, subdomain, partition, kind }, extra) => {
try {
const client = createClient(getToken(extra), partition);
const result = await client.sites.create({ domain, subdomain });
const result = await client.sites.create({ domain, subdomain, kind });
return {
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
};
Expand Down Expand Up @@ -423,7 +434,7 @@ Subdomain selection must respect the domain's capabilities from \`list_domains\`

server.tool(
"deploy_files",
"Publish in-memory file contents to a Hostsmith site without writing to disk. Use when you have just generated content (an HTML page, a report, JSON data) and the user wants it live. Returns the deployment version and status; call `get_site` afterwards if you need the public URL to share. The site must already exist - call `create_site` first if you do not have a `siteId`. Deploying to a site that already has content overwrites it - confirm overwrite with the user first.\n\n**Anti-pattern:** do not use this tool to ship binaries (images, PDFs, video, fonts, zips) by base64-embedding or data-URI inlining them into HTML/CSS/JSON. Binaries belong on `deploy_create_upload`. If that path is blocked by sandbox/network, escalate to the user (ask them to enable egress, or offer manual upload of the presigned URL) - never reach for this tool as a workaround. Inlining bloats pages, breaks browser caching, and reships the bytes on every deploy.",
"Publish in-memory file contents to a Hostsmith site without writing to disk. Use when you have just generated content (an HTML page, a report, JSON data) and the user wants it live. Returns the deployment version and status; call `get_site` afterwards if you need the public URL to share. The site must already exist - call `create_site` first if you do not have a `siteId`. Deploying to a site that already has content overwrites it - confirm overwrite with the user first. A redirect host (`kind: \"redirect\"`) takes no files and answers `RedirectHostHasNoFiles`: change its rules with the redirect tools instead.\n\n**Anti-pattern:** do not use this tool to ship binaries (images, PDFs, video, fonts, zips) by base64-embedding or data-URI inlining them into HTML/CSS/JSON. Binaries belong on `deploy_create_upload`. If that path is blocked by sandbox/network, escalate to the user (ask them to enable egress, or offer manual upload of the presigned URL) - never reach for this tool as a workaround. Inlining bloats pages, breaks browser caching, and reships the bytes on every deploy.",
{
siteId: z
.string()
Expand Down Expand Up @@ -478,7 +489,7 @@ Subdomain selection must respect the domain's capabilities from \`list_domains\`

server.tool(
"deploy_create_upload",
`Start a direct-to-S3 upload for binary or large files. Use this instead of \`deploy_files\` for binaries (PDF, image, video, zip) or any file > ~1 MB. The MCP server has no access to the user's filesystem and \`deploy_files\` ships content inline through Lambda (capped at ~6 MB JSON-RPC payloads); this tool returns presigned S3 PUT URLs so the file bytes flow directly from your environment to S3, never through the MCP server.
`Start a direct-to-S3 upload for binary or large files. Use this instead of \`deploy_files\` for binaries (PDF, image, video, zip) or any file > ~1 MB. The MCP server has no access to the user's filesystem and \`deploy_files\` ships content inline through Lambda (capped at ~6 MB JSON-RPC payloads); this tool returns presigned S3 PUT URLs so the file bytes flow directly from your environment to S3, never through the MCP server. A redirect host (\`kind: "redirect"\`) takes no files and answers \`RedirectHostHasNoFiles\`.

**Bundle into a zip first when:** the upload contains more than 3 files OR any file is larger than ~1 MB. The fileWorker auto-extracts a single-zip upload after promotion, so subdirectories are preserved end-to-end and you avoid one PUT round-trip per file. Skip zipping only for the trivial single-small-file case (e.g. one HTML).

Expand Down
106 changes: 106 additions & 0 deletions test/redirectHosts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { test, before, after, beforeEach } from "node:test";
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { createFetchHandler } from "../src/index.js";

// A redirect host is a site created with kind "redirect": create_site passes
// the kind on, and the deploy tools answer the API's refusal unchanged.

interface Seen {
method: string;
url: string;
body: unknown;
}

let seen: Seen[] = [];
let reply: { status: number; body: unknown } = { status: 200, body: {} };

const api = createServer((req, res) => {
let raw = "";
req.on("data", (chunk) => (raw += chunk));
req.on("end", () => {
seen.push({ method: req.method!, url: req.url!, body: raw ? JSON.parse(raw) : undefined });
res.writeHead(reply.status, { "content-type": "application/json" }).end(JSON.stringify(reply.body));
});
});

before(async () => {
await new Promise<void>((resolve) => api.listen(0, "127.0.0.1", resolve));
process.env.HOSTSMITH_BASE_URL = `http://127.0.0.1:${(api.address() as AddressInfo).port}`;
});

after(async () => {
delete process.env.HOSTSMITH_BASE_URL;
api.closeAllConnections();
await new Promise<void>((resolve) => api.close(() => resolve()));
});

beforeEach(() => {
seen = [];
reply = { status: 200, body: {} };
});

function makeToken(claims: Record<string, unknown>): string {
const part = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
return `${part({ alg: "RS256", typ: "JWT" })}.${part(claims)}.sig`;
}

async function rpc(method: string, params: unknown) {
const handler = createFetchHandler({ hostsmithUrl: "https://hostsmith.net", mcpBaseUrl: "http://localhost:3100" });
const token = makeToken({ sub: "user-1", scope: "sites:read sites:write", homePartition: "us", exp: Math.floor(Date.now() / 1000) + 3600 });
const res = await handler(
new Request("http://localhost:3100/mcp", {
method: "POST",
headers: {
"content-type": "application/json",
accept: "application/json, text/event-stream",
authorization: `Bearer ${token}`,
},
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
}),
);
const data = (await res.text()).split("\n").find((line) => line.startsWith("data: "));
assert.ok(data, "expected an SSE data line");
return JSON.parse(data.slice("data: ".length)).result;
}

async function callTool(name: string, args: Record<string, unknown>): Promise<{ text: string; isError?: boolean }> {
const result = await rpc("tools/call", { name, arguments: args });
return { text: result.content[0].text, isError: result.isError };
}

test("create_site takes the kind of site", async () => {
const { tools } = await rpc("tools/list", {});
const createSite = tools.find((tool: { name: string }) => tool.name === "create_site");
assert.deepEqual(createSite.inputSchema.properties.kind.enum, ["site", "redirect"]);
assert.ok(!createSite.inputSchema.required.includes("kind"));
});

test("create_site sends the kind of a redirect host, and no kind when omitted", async () => {
reply = { status: 201, body: { siteId: "h1" } };
await callTool("create_site", { domain: "example.com", subdomain: "go", kind: "redirect" });
await callTool("create_site", { domain: "example.com", subdomain: "www" });

assert.equal(seen[0].method, "POST");
assert.equal(seen[0].url, "/v1/sites");
assert.deepEqual(seen[0].body, { domain: "example.com", subdomain: "go", kind: "redirect" });
assert.deepEqual(seen[1].body, { domain: "example.com", subdomain: "www" });
});

test("a redirect host on a shared domain is refused with the API's code", async () => {
reply = { status: 409, body: { error: "CustomDomainRequired", message: "Redirect hosts work only on the organization's own custom domains" } };
const result = await callTool("create_site", { domain: "us.hostsmith.link", subdomain: "go", kind: "redirect" });

assert.equal(result.isError, true);
assert.equal(result.text, "API error 409 (CustomDomainRequired): Redirect hosts work only on the organization's own custom domains");
});

test("deploy_files to a redirect host answers RedirectHostHasNoFiles", async () => {
reply = { status: 409, body: { error: "RedirectHostHasNoFiles", message: "Redirect hosts have no files: change their redirect rules instead" } };
const result = await callTool("deploy_files", { siteId: "h1", files: [{ fileName: "index.html", content: "<h1>Hi</h1>" }] });

assert.equal(seen[0].url, "/v1/sites/h1/uploads");
assert.equal(result.isError, true);
assert.equal(result.text, "API error 409 (RedirectHostHasNoFiles): Redirect hosts have no files: change their redirect rules instead");
});
Loading