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
11 changes: 11 additions & 0 deletions .changesets/1794462313-1f3dc8f5.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
id: 1794462313-1f3dc8f5
features:
- core
targets:
- typescriptv2
- mcp-typescript
type: fix
bump: patch
description: "behaviour change: operation path parameter values that form . or .. URL segments are now rejected with an InvalidRequestError (an MCP tool error for MCP servers) instead of sending the request to a different route"
author: TristanSpeakEasy
date: "2026-11-12"
1 change: 1 addition & 0 deletions templates/perms.go
Original file line number Diff line number Diff line change
Expand Up @@ -1227,6 +1227,7 @@ var fileMode = map[string]fs.FileMode{
"templates/mcp-typescript/tests/lib/async.test.ts.stmpl": 0o644,
"templates/mcp-typescript/tests/lib/oauth2-sessions.test.ts.stmpl": 0o644,
"templates/mcp-typescript/tests/lib/schemas.test.ts.stmpl": 0o644,
"templates/mcp-typescript/tests/lib/url.test.ts": 0o644,
"templates/mcp-typescript/tests/primary": 0o20000000755,
"templates/mcp-typescript/tests/primary/auth_additional.test.ts.stmpl": 0o644,
"templates/mcp-typescript/tests/primary/authnew_additional.test.ts.stmpl": 0o644,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { Logger } from "./logger.js";
import { encodeForm } from "./encodings.js";
import { stringToBase64 } from "./base64.js";
import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js";
import { Params, pathToFunc } from "./url.js";
import { SDKHooks } from "../hooks/hooks.js";
import { HookContext } from "../hooks/types.js";
{{- if and .Global.Config.EnvVarPrefix .Global.AST.MainSDK.Globals }}
Expand Down Expand Up @@ -61,6 +62,21 @@ type RequestConfig = {
timeoutMs?: number;
};

{{- addErrorTypeImport "InvalidRequestError" "lib" }}

export function encodePath(
pathPattern: string,
params: Params,
): Result<string, InvalidRequestError> {
try {
return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params));
} catch (err: unknown) {
return ERR(
new InvalidRequestError(err instanceof Error ? err.message : String(err)),
);
}
}

const gt: unknown = typeof globalThis === "undefined" ? null : globalThis;
const webWorkerLike =
typeof gt === "object" &&
Expand Down Expand Up @@ -391,6 +407,7 @@ import { Logger } from "./logger.js";
import { encodeForm } from "./encodings.js";
import { stringToBase64 } from "./base64.js";
import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js";
import { Params, pathToFunc } from "./url.js";
import { SDKHooks } from "../hooks/hooks.js";
import { HookContext } from "../hooks/types.js";
{{- if and .Global.Config.EnvVarPrefix .Global.AST.MainSDK.Globals }}
Expand Down Expand Up @@ -441,6 +458,21 @@ type RequestConfig = {
timeoutMs?: number;
};

{{- addErrorTypeImport "InvalidRequestError" "lib" }}

export function encodePath(
pathPattern: string,
params: Params,
): Result<string, InvalidRequestError> {
try {
return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params));
} catch (err: unknown) {
return ERR(
new InvalidRequestError(err instanceof Error ? err.message : String(err)),
);
}
}

const gt: unknown = typeof globalThis === "undefined" ? null : globalThis;
const webWorkerLike =
typeof gt === "object" &&
Expand Down
83 changes: 65 additions & 18 deletions templates/templates/mcp-typescript/auxiliary/src/lib/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,75 @@ const hasOwn = Object.prototype.hasOwnProperty;

export type Params = Partial<Record<string, string | number>>;

// WHATWG URL parsing strips tab and newline characters, ends the path at "?" or
// "#", treats "\" as "/" in special schemes, and resolves "%2e" as "." when
// removing dot segments.
const ignoredURLCharsRE = /[\t\n\r]/g;
const pathEndRE = /[?#]/;
const segmentSeparatorRE = /[/\\]/;
const dotSegmentRE = /^(?:\.|%2e){1,2}$/i;

function hasDotSegment(value: string): boolean {
const path = value.replace(ignoredURLCharsRE, "").split(pathEndRE, 1)[0];
return (path ?? "")
.split(segmentSeparatorRE)
.some((part) => dotSegmentRE.test(part));
}

function dotSegmentError(names: string[]): Error {
const subject =
names.length === 1
? `Parameter '${names[0]}'`
: `Parameters '${names.join("', '")}'`;
return new Error(`${subject} must not form a '.' or '..' path segment`);
}

export function pathToFunc(
pathPattern: string,
options?: { charEncoding?: "percent" | "none" },
options?: {
charEncoding?: "percent" | "none";
rejectDotSegments?: boolean;
},
): (params?: Params) => string {
const paramRE = /\{([a-zA-Z0-9_]+?)\}/g;
const paramRE = /\{([a-zA-Z0-9_][a-zA-Z0-9_-]*?)\}/g;

return function buildURLPath(params: Record<string, unknown> = {}): string {
return pathPattern.replace(paramRE, function (_, placeholder) {
if (!hasOwn.call(params, placeholder)) {
throw new Error(`Parameter '${placeholder}' is required`);
}

const value = params[placeholder];
if (typeof value !== "string" && typeof value !== "number") {
throw new Error(
`Parameter '${placeholder}' must be a string or number`,
);
}

return options?.charEncoding === "percent"
? encodeURIComponent(`${value}`)
: `${value}`;
});
return pathPattern
.split("/")
.map((segment) => {
const contributors: string[] = [];
const rendered = segment.replace(paramRE, function (_, placeholder) {
if (!hasOwn.call(params, placeholder)) {
throw new Error(`Parameter '${placeholder}' is required`);
}

const value = params[placeholder];
if (typeof value !== "string" && typeof value !== "number") {
throw new Error(
`Parameter '${placeholder}' must be a string or number`,
);
}

const encoded =
options?.charEncoding === "percent"
? encodeURIComponent(`${value}`)
: `${value}`;
if (encoded !== "") {
contributors.push(placeholder);
}
return encoded;
});

if (
options?.rejectDotSegments &&
contributors.length > 0 &&
hasDotSegment(rendered)
) {
throw dotSegmentError(contributors);
}

return rendered;
})
.join("/");
};
}
30 changes: 18 additions & 12 deletions templates/templates/mcp-typescript/func.ts.stmpl
Original file line number Diff line number Diff line change
Expand Up @@ -236,13 +236,16 @@ async function $do(
{{ sanitizeKey $spec.name}}: {{ genSingleParamEncoder $spec.fieldDef $spec.accessor }},
{{- end }}
};
{{- end}}
{{- addInternalImport "sdks" "encodePath" "funcs" }}
const pathResult$ = encodePath("{{ $op.Path }}", pathParams$);
if (!pathResult$.ok) {
return [pathResult$, { status: "invalid" }];
}
const path$ = pathResult$.value;
{{- else }}
{{- addInternalImport "url" "pathToFunc" "funcs" }}
const path$ = pathToFunc("{{ $op.Path }}")(
{{- if $hasPathParams }}
pathParams$,
{{- end }}
);
const path$ = pathToFunc("{{ $op.Path }}")();
{{- end}}

{{- if $hasQueryParams }}
const query$ = {{genQueryParamEncoder $requestParams.query}};
Expand Down Expand Up @@ -669,13 +672,16 @@ async function $do(
{{ sanitizeKey $spec.name}}: {{ genSingleParamEncoder $spec.fieldDef $spec.accessor }},
{{- end }}
};
{{- end}}
{{- addInternalImport "sdks" "encodePath" "funcs" }}
const pathResult$ = encodePath("{{ $op.Path }}", pathParams$);
if (!pathResult$.ok) {
return [pathResult$, { status: "invalid" }];
}
const path$ = pathResult$.value;
{{- else }}
{{- addInternalImport "url" "pathToFunc" "funcs" }}
const path$ = pathToFunc("{{ $op.Path }}")(
{{- if $hasPathParams }}
pathParams$,
{{- end }}
);
const path$ = pathToFunc("{{ $op.Path }}")();
{{- end}}

{{- if $hasQueryParams }}
const query$ = {{genQueryParamEncoder $requestParams.query}};
Expand Down
107 changes: 107 additions & 0 deletions templates/templates/mcp-typescript/tests/lib/url.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { describe, expect, test } from "vitest";

import { pathToFunc } from "../../lib/url.js";

test.each<
[
title: string,
pattern: string,
args: Record<string, string | number>,
output: string | Error,
]
>([
["no placeholders", "/sample/path", {}, "/sample/path"],
["one placeholder", "/author/{id}/likes", { id: 123 }, "/author/123/likes"],
[
"infix placeholder",
"/entity/user-{id}/",
{ id: "1893" },
"/entity/user-1893/",
],
[
"placeholder with hyphen",
"/foo/bar/{thing-blah}",
{ "thing-blah": "test-value" },
"/foo/bar/test-value",
],
[
"insufficient params",
"/blog/{slug}/comments/{commentId}",
{ slug: "hello-world" },
new Error("Parameter 'commentId' is required"),
],
])("pathToFunc: %s", (_, pattern, args, output) => {
if (output instanceof Error) {
expect(() => pathToFunc(pattern)(args)).toThrow(output);
} else {
expect(pathToFunc(pattern)(args)).toEqual(output);
}
});

describe("pathToFunc dot segments", () => {
const pattern = "/stores/{store_id}/items/{item_id}/details";
const dotSegmentError =
/^Parameter 'store_id' must not form a '\.' or '\.\.' path segment$/;
const checked = (
path: string,
options?: { charEncoding?: "percent" | "none" },
) => pathToFunc(path, { ...options, rejectDotSegments: true });

test.each(["..", ".", "%2e%2e", ".%2E", "a/../b", "..\\b", "..?x", ".\t."])(
"rejects %j",
(value) => {
expect(() =>
checked(pattern)({ store_id: value, item_id: "item-1" }),
).toThrow(dotSegmentError);
},
);

test.each([".", ".."])("rejects %j under percent encoding", (value) => {
expect(() =>
checked(pattern, { charEncoding: "percent" })({
store_id: value,
item_id: "item-1",
}),
).toThrow(dotSegmentError);
});

test("rejects dot segments from hyphenated placeholders", () => {
expect(() => checked("/x/{thing-blah}")({ "thing-blah": ".." })).toThrow(
/^Parameter 'thing-blah' must not form/,
);
});

test("names every placeholder that contributes to the dot segment", () => {
expect(() => checked("/x/{a}{b}/y")({ a: ".", b: "." })).toThrow(
"Parameters 'a', 'b' must not form a '.' or '..' path segment",
);
expect(() => checked("/x/{a}{b}/y")({ a: "..", b: "" })).toThrow(
/^Parameter 'a' must not form/,
);
});

test.each(["...", ".hidden", "v1.2.3", "a..b", "safe?next=/.."])(
"allows %j",
(value) => {
expect(checked(pattern)({ store_id: value, item_id: "item-1" })).toEqual(
`/stores/${value}/items/item-1/details`,
);
},
);

test("leaves literal template segments unchanged", () => {
expect(checked("/v1/../{id}")({ id: "x" })).toEqual("/v1/../x");
expect(checked("/entity/user-{id}")({ id: ".." })).toEqual(
"/entity/user-..",
);
});

test("does not check templates unless rejectDotSegments is set", () => {
expect(pathToFunc("https://{host}/x")({ host: ".." })).toEqual(
"https://../x",
);
expect(pathToFunc(pattern)({ store_id: "..", item_id: "item-1" })).toEqual(
"/stores/../items/item-1/details",
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,27 @@ import { parametersPathParameterJson } from "../funcs/parametersPathParameterJso
import { parametersJsonQueryParamsObject } from "../funcs/parametersJsonQueryParamsObject.js";
import { parametersMixedQueryParams } from "../funcs/parametersMixedQueryParams.js";
import { parametersHeaderParamsNil } from "../funcs/parametersHeaderParamsNil.js";
import { parametersPathEncoding } from "../funcs/parametersPathEncoding.js";
import { InvalidRequestError } from "../models/errors/httpclienterrors.js";
{{ if isStrictMCPServer }}
const roundTrip = (v: unknown) => JSON.parse(JSON.stringify(v));
{{- end }}

test("Test Path Dot Segment Rejection", async () => {
const result = await parametersPathEncoding(new SDK({}), {
Comment thread
TristanSpeakEasy marked this conversation as resolved.
Resolved
param1: "..",
param2: "value",
});

expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toBeInstanceOf(InvalidRequestError);
expect(result.error.message).toBe(
"Parameter 'param1' must not form a '.' or '..' path segment",
);
}
});

test("Test Path Parameter JSON", async () => {
recordTest("parameters-path-parameter-json");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Logger } from "./logger.js";
import { encodeForm } from "./encodings.js";
import { stringToBase64 } from "./base64.js";
import { SDKOptions, SDK_METADATA, serverURLFromOptions } from "./config.js";
import { Params, pathToFunc } from "./url.js";
import { SDKHooks } from "../hooks/hooks.js";
import { HookContext } from "../hooks/types.js";
{{- if and .Global.Config.EnvVarPrefix .Global.AST.MainSDK.Globals }}
Expand Down Expand Up @@ -82,6 +83,20 @@ type RequestConfig = {
{{constants.timeoutMs}}?: number;
};

{{ addErrorTypeImport "InvalidRequestError" "lib" }}
export function encodePath(
pathPattern: string,
params: Params,
): Result<string, InvalidRequestError> {
try {
return OK(pathToFunc(pathPattern, { rejectDotSegments: true })(params));
} catch (err: unknown) {
return ERR(
new InvalidRequestError(err instanceof Error ? err.message : String(err)),
);
}
}

const gt: unknown = typeof globalThis === "undefined" ? null : globalThis;
const webWorkerLike =
typeof gt === "object" &&
Expand Down
Loading
Loading