Skip to content
Open
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
8 changes: 8 additions & 0 deletions .changeset/uri-template-semicolon-and-empty-lists.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@modelcontextprotocol/core-internal': patch
'@modelcontextprotocol/server': patch
---

Support the RFC 6570 path-style parameter operator (`;`) in URI templates: templates such as `{;x,y}` now expand to `;x=1;y=2` (and `;name` when the value is empty), and `UriTemplate#match` parses those segments back into variables. Also treat a list with zero members as undefined, as RFC 6570 allows, so `/tags{/tags}`, `/tags{?tags}`, `X{.tags}` and `X{;tags}` no longer leave a dangling separator or an empty `name=` pair when the list is empty.

Known limitation: an exploded `;` list with exactly one member expands to `;list=red` and matches back as the string `'red'`, not `['red']`; a zero-member list expands to nothing and therefore does not match. Both come from the existing `string | string[]` `Variables` type and the `+` in the repeated pattern, not from this change.
78 changes: 66 additions & 12 deletions packages/core-internal/src/shared/uriTemplate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export class UriTemplate {
}

private getOperator(expr: string): string {
const operators = ['+', '#', '.', '/', '?', '&'];
const operators = ['+', '#', '.', '/', '?', '&', ';'];
return operators.find(op => expr.startsWith(op)) || '';
}

Expand All @@ -101,6 +101,11 @@ export class UriTemplate {
.filter(name => name.length > 0);
}

// RFC 6570 Section 2.3: a list with zero members is considered undefined.
private isUndefinedValue(value: string | string[] | undefined): value is undefined {
return value === undefined || (Array.isArray(value) && value.length === 0);
}

private encodeValue(value: string, operator: string): string {
UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value');
if (operator === '+' || operator === '#') {
Expand All @@ -122,7 +127,7 @@ export class UriTemplate {
const pairs = part.names
.map(name => {
const value = variables[name];
if (value === undefined) return '';
if (this.isUndefinedValue(value)) return '';
const encoded = Array.isArray(value)
? value.map(v => this.encodeValue(v, part.operator)).join(',')
: this.encodeValue(value.toString(), part.operator);
Expand All @@ -135,14 +140,30 @@ export class UriTemplate {
return separator + pairs.join('&');
}

if (part.operator === ';') {
const segments = part.names.flatMap(name => {
const value = variables[name];
if (this.isUndefinedValue(value)) return [];
if (part.exploded && Array.isArray(value)) {
return value.map(v => `;${name}=${this.encodeValue(v, part.operator)}`);
}
const encoded = Array.isArray(value)
? value.map(v => this.encodeValue(v, part.operator)).join(',')
: this.encodeValue(value.toString(), part.operator);
// RFC 6570 Section 3.2.7: append "=" only when the value is not empty.
return [encoded ? `;${name}=${encoded}` : `;${name}`];
});
return segments.join('');
}

if (part.names.length > 1) {
const values = part.names.map(name => variables[name]).filter(v => v !== undefined);
const values = part.names.map(name => variables[name]).filter(v => !this.isUndefinedValue(v));
if (values.length === 0) return '';
return values.map(v => (Array.isArray(v) ? v[0] : v)).join(',');
}

const value = variables[part.name];
if (value === undefined) return '';
if (this.isUndefinedValue(value)) return '';

const values = Array.isArray(value) ? value : [value];
const encoded = values.map(v => this.encodeValue(v, part.operator));
Expand Down Expand Up @@ -202,8 +223,8 @@ export class UriTemplate {
operator: string;
names: string[];
exploded: boolean;
}): Array<{ pattern: string; name: string }> {
const patterns: Array<{ pattern: string; name: string }> = [];
}): Array<{ pattern: string; name: string; repeated?: boolean; splitOnComma?: boolean }> {
const patterns: Array<{ pattern: string; name: string; repeated?: boolean; splitOnComma?: boolean }> = [];

// Validate variable name length for matching
for (const name of part.names) {
Expand All @@ -222,6 +243,25 @@ export class UriTemplate {
return patterns;
}

if (part.operator === ';') {
for (let i = 0; i < part.names.length; i++) {
const name = part.names[i]!;
if (part.exploded) {
// RFC 6570 Section 3.2.7 repeats the `;name=value` segment for exploded lists, and
// JavaScript keeps only the last iteration of `(?:;name=([^;]*))+`, so the pattern
// captures the whole run and `match` splits it into the member values.
patterns.push({ pattern: '((?:;' + this.escapeRegExp(name) + '(?:=[^;]*)?)+)', name, repeated: true });
} else {
patterns.push({
pattern: ';' + this.escapeRegExp(name) + '(?:=([^;]*))?',
name,
splitOnComma: true
});
}
}
return patterns;
}

let pattern: string;
const name = part.name;

Expand Down Expand Up @@ -255,16 +295,16 @@ export class UriTemplate {
match(uri: string): Variables | null {
UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI');
let pattern = '^';
const names: Array<{ name: string; exploded: boolean }> = [];
const names: Array<{ name: string; exploded: boolean; repeated?: boolean; splitOnComma?: boolean }> = [];

for (const part of this.parts) {
if (typeof part === 'string') {
pattern += this.escapeRegExp(part);
} else {
const patterns = this.partToRegExp(part);
for (const { pattern: partPattern, name } of patterns) {
for (const { pattern: partPattern, name, repeated, splitOnComma } of patterns) {
pattern += partPattern;
names.push({ name, exploded: part.exploded });
names.push({ name, exploded: part.exploded, repeated, splitOnComma });
}
}
}
Expand All @@ -278,11 +318,25 @@ export class UriTemplate {

const result: Variables = {};
for (const [i, name_] of names.entries()) {
const { name, exploded } = name_!;
const value = match[i + 1]!;
const { name, exploded, repeated, splitOnComma } = name_!;
// The `=` group is optional, which is how `{;empty}` matches the bare `;empty` that expand
// produces; an absent capture reads as '' rather than leaving the variable out.
const value = match[i + 1] ?? '';
const cleanName = name.replace('*', '');

result[cleanName] = exploded && value.includes(',') ? value.split(',') : value;
if (repeated) {
const values = value
.split(';')
.filter(segment => segment.length > 0)
.map(segment => {
const equals = segment.indexOf('=');
return equals === -1 ? '' : segment.slice(equals + 1);
});
result[cleanName] = values.length > 1 ? values : (values[0] ?? '');
continue;
}

result[cleanName] = (exploded || splitOnComma) && value.includes(',') ? value.split(',') : value;
}

return result;
Expand Down
92 changes: 92 additions & 0 deletions packages/core-internal/test/shared/uriTemplate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,98 @@ describe('UriTemplate', () => {
});
});

describe('path-style parameter expansion', () => {
it('should add ; prefix and name=value format', () => {
const template = new UriTemplate('{;x,y}');
expect(template.expand({ x: '1024', y: '768' })).toBe(';x=1024;y=768');
expect(template.variableNames).toEqual(['x', 'y']);
});

it('should match the RFC 6570 Section 3.2.7 examples', () => {
expect(new UriTemplate('{;who}').expand({ who: 'fred' })).toBe(';who=fred');
expect(new UriTemplate('{;half}').expand({ half: '50%' })).toBe(';half=50%25');
expect(new UriTemplate('{;empty}').expand({ empty: '' })).toBe(';empty');
expect(new UriTemplate('{;v,empty,who}').expand({ v: '6', empty: '', who: 'fred' })).toBe(';v=6;empty;who=fred');
expect(new UriTemplate('{;v,bar,who}').expand({ v: '6', who: 'fred' })).toBe(';v=6;who=fred');
expect(new UriTemplate('{;x,y,empty}').expand({ x: '1024', y: '768', empty: '' })).toBe(';x=1024;y=768;empty');
expect(new UriTemplate('{;x,y,undef}').expand({ x: '1024', y: '768' })).toBe(';x=1024;y=768');
expect(new UriTemplate('{;list}').expand({ list: ['red', 'green', 'blue'] })).toBe(';list=red,green,blue');
expect(new UriTemplate('{;list*}').expand({ list: ['red', 'green', 'blue'] })).toBe(';list=red;list=green;list=blue');
// `{;keys}` and `{;keys*}` are not covered: RFC 6570 associative values cannot be represented by
// `Variables`, which only holds strings and lists of strings.
// `{;hello:5}` is not covered either: prefix modifiers are not parsed, a pre-existing gap.
});

it('should expand path parameters after a literal path segment', () => {
expect(new UriTemplate('X{;color,year}').expand({ color: 'red', year: '2012' })).toBe('X;color=red;year=2012');
});

it('should encode values as unreserved characters', () => {
expect(new UriTemplate('{;v}').expand({ v: 'a b' })).toBe(';v=a%20b');
expect(new UriTemplate('{;v}').expand({ v: 'a;b=c' })).toBe(';v=a%3Bb%3Dc');
});

it('should match ;name=value segments back to variables', () => {
expect(new UriTemplate('{;x}').match(';x=1')).toEqual({ x: '1' });
expect(new UriTemplate('{;x,y}').match(';x=1;y=2')).toEqual({ x: '1', y: '2' });
expect(new UriTemplate('X{;color,year}').match('X;color=red;year=2012')).toEqual({
color: 'red',
year: '2012'
});
expect(new UriTemplate('{;empty}').match(';empty')).toEqual({ empty: '' });
});

it('should round-trip an exploded path-style list through match', () => {
const template = new UriTemplate('{;list*}');
const uri = template.expand({ list: ['red', 'green', 'blue'] });
expect(uri).toBe(';list=red;list=green;list=blue');
expect(template.match(uri)).toEqual({ list: ['red', 'green', 'blue'] });
expect(template.match(';list=red')).toEqual({ list: 'red' });
});

it('should round-trip a non-exploded path-style list through match', () => {
const template = new UriTemplate('{;list}');
const uri = template.expand({ list: ['red', 'green', 'blue'] });
expect(uri).toBe(';list=red,green,blue');
expect(template.match(uri)).toEqual({ list: ['red', 'green', 'blue'] });
});

it('should return null when path-style parameters do not match', () => {
expect(new UriTemplate('{;x}').match('?x=1')).toBeNull();
expect(new UriTemplate('{;x}').match(';y=1')).toBeNull();
});
});

describe('empty list expansion', () => {
it('should treat a list with zero members as undefined', () => {
expect(new UriTemplate('{tags}').expand({ tags: [] })).toBe('');
expect(new UriTemplate('{+tags}').expand({ tags: [] })).toBe('');
expect(new UriTemplate('X{#tags}').expand({ tags: [] })).toBe('X');
expect(new UriTemplate('X{.tags}').expand({ tags: [] })).toBe('X');
expect(new UriTemplate('X{/tags}').expand({ tags: [] })).toBe('X');
expect(new UriTemplate('X{?tags}').expand({ tags: [] })).toBe('X');
expect(new UriTemplate('X{&tags}').expand({ tags: [] })).toBe('X');
expect(new UriTemplate('X{;tags}').expand({ tags: [] })).toBe('X');
});

it('should not leave a dangling separator behind', () => {
expect(new UriTemplate('/tags{/tags}').expand({ tags: [] })).toBe('/tags');
expect(new UriTemplate('/tags{?tags}').expand({ tags: [] })).toBe('/tags');
expect(new UriTemplate('/tags{.tags}').expand({ tags: [] })).toBe('/tags');
expect(new UriTemplate('/tags{;tags}').expand({ tags: [] })).toBe('/tags');
});

it('should still expand defined empty strings', () => {
expect(new UriTemplate('{;empty}').expand({ empty: '' })).toBe(';empty');
expect(new UriTemplate('{?empty}').expand({ empty: '' })).toBe('?empty=');
});

it('should skip empty lists inside multi-variable expressions', () => {
expect(new UriTemplate('{;x,y}').expand({ x: '1', y: [] })).toBe(';x=1');
expect(new UriTemplate('X{?a,b}').expand({ a: '1', b: [] })).toBe('X?a=1');
});
});

describe('security and edge cases', () => {
it('should handle extremely long input strings', () => {
const longString = 'x'.repeat(100_000);
Expand Down
Loading