-
Notifications
You must be signed in to change notification settings - Fork 338
feat: add snippet CRUD tools #470
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
renanliberato
wants to merge
8
commits into
zereight:main
Choose a base branch
from
renanliberato:feat/snippets
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
0cc256a
feat: add snippet CRUD tools
renanliberato ff89d36
fix: extract ref from raw_url to fetch multi-file snippet content
renanliberato d2be004
refactor: align snippet file ref handling with repository/files pattern
renanliberato a5314e8
fix: address snippet tool review feedback
renanliberato 68b4aa6
fix: require previous_path on snippet files[] move action
renanliberato ebc0f2b
fix: allow explicit ref when snippet file has no raw_url
renanliberato be277ab
fix: enforce project scope on omitted project_id for snippets
renanliberato 79eb6d6
fix: validate per-action snippet file requirements at parse time
renanliberato File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -356,6 +356,13 @@ import { | |
| GitLabTagSignatureSchema, | ||
| type GitLabTag, | ||
| type GitLabTagSignature, | ||
| ListSnippetsSchema, | ||
| GetSnippetSchema, | ||
| CreateSnippetSchema, | ||
| UpdateSnippetSchema, | ||
| DeleteSnippetSchema, | ||
| GitLabSnippetSchema, | ||
| type GitLabSnippet, | ||
| GetMergeRequestNotesSchema, | ||
| GetMergeRequestNoteSchema, | ||
| DeleteMergeRequestDiscussionNoteSchema, | ||
|
|
@@ -8303,6 +8310,201 @@ async function getTagSignature( | |
| return GitLabTagSignatureSchema.parse(data); | ||
| } | ||
|
|
||
| /** | ||
| * Build the snippets endpoint URL. | ||
| * | ||
| * When projectId is provided, or when project scoping is configured via | ||
| * GITLAB_PROJECT_ID / GITLAB_ALLOWED_PROJECT_IDS, returns the project snippets | ||
| * endpoint (routing through getEffectiveProjectId so the scope env is enforced). | ||
| * Only falls back to the personal /snippets endpoint when neither is set. | ||
| */ | ||
| function getSnippetsEndpoint(projectId?: string): string { | ||
| const scopeActive = GITLAB_ALLOWED_PROJECT_IDS.length > 0 || !!GITLAB_PROJECT_ID; | ||
| if (projectId || scopeActive) { | ||
| const decoded = projectId ? decodeURIComponent(projectId) : ""; | ||
| const effectiveProjectId = getEffectiveProjectId(decoded); | ||
| return `${getEffectiveApiUrl()}/projects/${encodeURIComponent(effectiveProjectId)}/snippets`; | ||
| } | ||
| return `${getEffectiveApiUrl()}/snippets`; | ||
| } | ||
|
|
||
| /** | ||
| * List snippets — project snippets if projectId is given, otherwise personal snippets. | ||
| */ | ||
| async function listSnippets( | ||
| projectId: string | undefined, | ||
| options: Omit<z.infer<typeof ListSnippetsSchema>, "project_id"> = {} | ||
| ): Promise<GitLabSnippet[]> { | ||
| const url = new URL(getSnippetsEndpoint(projectId)); | ||
|
|
||
| Object.entries(options).forEach(([key, value]) => { | ||
| if (value !== undefined) { | ||
| url.searchParams.append(key, String(value)); | ||
| } | ||
| }); | ||
|
|
||
| const response = await fetch(url.toString(), { | ||
| ...getFetchConfig(), | ||
| }); | ||
|
|
||
| await handleGitLabError(response); | ||
|
|
||
| const data = await response.json(); | ||
| return GitLabSnippetSchema.array().parse(data); | ||
| } | ||
|
|
||
| /** | ||
| * Get a snippet's metadata. Use getSnippetRawContent to fetch the raw file content. | ||
| */ | ||
| async function getSnippet( | ||
| projectId: string | undefined, | ||
| snippetId: number | ||
| ): Promise<GitLabSnippet> { | ||
| const response = await fetch(`${getSnippetsEndpoint(projectId)}/${snippetId}`, { | ||
| ...getFetchConfig(), | ||
| }); | ||
|
|
||
| await handleGitLabError(response); | ||
|
|
||
| const data = await response.json(); | ||
| return GitLabSnippetSchema.parse(data); | ||
| } | ||
|
|
||
| /** | ||
| * Get the raw content of a single-file snippet via the `/raw` endpoint. | ||
| * For multi-file snippets, use getSnippetFileRawContent instead. | ||
| */ | ||
| async function getSnippetRawContent( | ||
| projectId: string | undefined, | ||
| snippetId: number | ||
| ): Promise<string> { | ||
| const response = await fetch(`${getSnippetsEndpoint(projectId)}/${snippetId}/raw`, { | ||
| ...getFetchConfig(), | ||
| }); | ||
|
|
||
| await handleGitLabError(response); | ||
|
|
||
| return await response.text(); | ||
| } | ||
|
|
||
| /** | ||
| * Extract the ref (branch/tag/commit) from a snippet file's raw_url. | ||
| * Anchors on /snippets/{id}/raw/ so branch names or file paths containing | ||
| * the word "raw" don't produce a false match. | ||
| */ | ||
| function extractSnippetRef(rawUrl: string, snippetId: number, filePath: string): string { | ||
| const rawMarker = `/snippets/${snippetId}/raw/`; | ||
| const decoded = decodeURIComponent(new URL(rawUrl).pathname); | ||
| const markerIdx = decoded.indexOf(rawMarker); | ||
| if (markerIdx === -1) { | ||
| throw new Error(`Cannot extract ref from snippet file raw_url: ${rawUrl}`); | ||
| } | ||
| const afterRaw = decoded.slice(markerIdx + rawMarker.length); // "{ref}/{filePath}" | ||
| const fileStart = afterRaw.lastIndexOf("/" + filePath); | ||
| if (fileStart === -1) { | ||
| throw new Error(`Cannot locate file path "${filePath}" in snippet file raw_url: ${rawUrl}`); | ||
| } | ||
| return afterRaw.slice(0, fileStart); | ||
| } | ||
|
|
||
| /** | ||
| * Fetch the raw content of one file inside a multi-file snippet. | ||
| * Accepts an explicit ref (branch/tag/commit) — callers resolve it via | ||
| * extractSnippetRef or a user-supplied parameter before calling this. | ||
| */ | ||
| async function getSnippetFileRawContent( | ||
| projectId: string | undefined, | ||
| snippetId: number, | ||
| ref: string, | ||
| filePath: string | ||
| ): Promise<string> { | ||
| const encodedRef = encodeURIComponent(ref); | ||
| const encodedPath = encodeURIComponent(filePath); | ||
| const url = `${getSnippetsEndpoint(projectId)}/${snippetId}/files/${encodedRef}/${encodedPath}/raw`; | ||
| const response = await fetch(url, { ...getFetchConfig() }); | ||
| await handleGitLabError(response); | ||
| return await response.text(); | ||
| } | ||
|
|
||
| /** | ||
| * Create a snippet — project-scoped if projectId is given, otherwise personal. | ||
| */ | ||
| async function createSnippet( | ||
| projectId: string | undefined, | ||
| options: Omit<z.infer<typeof CreateSnippetSchema>, "project_id"> | ||
| ): Promise<GitLabSnippet> { | ||
| const { title, file_name, content, files, description, visibility } = options; | ||
| const filesPayload = | ||
| files && files.length > 0 | ||
| ? files | ||
| : [{ file_path: file_name as string, content: content as string }]; | ||
| const body: Record<string, unknown> = { | ||
| title, | ||
| visibility: visibility ?? "private", | ||
| files: filesPayload, | ||
| }; | ||
| if (description !== undefined) { | ||
| body.description = description; | ||
| } | ||
|
|
||
| const response = await fetch(getSnippetsEndpoint(projectId), { | ||
| ...getFetchConfig(), | ||
| method: "POST", | ||
| body: JSON.stringify(body), | ||
| }); | ||
|
|
||
| await handleGitLabError(response); | ||
|
|
||
| const data = await response.json(); | ||
| return GitLabSnippetSchema.parse(data); | ||
| } | ||
|
|
||
| /** | ||
| * Update an existing snippet — project-scoped if projectId is given, otherwise personal. | ||
| */ | ||
| async function updateSnippet( | ||
| projectId: string | undefined, | ||
| options: Omit<z.infer<typeof UpdateSnippetSchema>, "project_id"> | ||
| ): Promise<GitLabSnippet> { | ||
| const { snippet_id, title, file_name, content, files, description, visibility } = options; | ||
| const body: Record<string, unknown> = {}; | ||
| if (title !== undefined) body.title = title; | ||
| if (description !== undefined) body.description = description; | ||
| if (visibility !== undefined) body.visibility = visibility; | ||
|
|
||
| if (files !== undefined) { | ||
| body.files = files; | ||
| } else if (file_name !== undefined && content !== undefined) { | ||
| body.files = [{ action: "update", file_path: file_name, content }]; | ||
| } | ||
|
|
||
| const response = await fetch(`${getSnippetsEndpoint(projectId)}/${snippet_id}`, { | ||
| ...getFetchConfig(), | ||
| method: "PUT", | ||
| body: JSON.stringify(body), | ||
| }); | ||
|
|
||
| await handleGitLabError(response); | ||
|
|
||
| const data = await response.json(); | ||
| return GitLabSnippetSchema.parse(data); | ||
| } | ||
|
|
||
| /** | ||
| * Delete a snippet — project-scoped if projectId is given, otherwise personal. | ||
| */ | ||
| async function deleteSnippet( | ||
| projectId: string | undefined, | ||
| snippetId: number | ||
| ): Promise<void> { | ||
| const response = await fetch(`${getSnippetsEndpoint(projectId)}/${snippetId}`, { | ||
| ...getFetchConfig(), | ||
| method: "DELETE", | ||
| }); | ||
|
|
||
| await handleGitLabError(response); | ||
| } | ||
|
|
||
| // Request handlers are now registered inside createServer() factory function | ||
| // to ensure each transport connection gets its own Server instance (GHSA-345p-7cg4-v4c7). | ||
|
|
||
|
|
@@ -10404,6 +10606,86 @@ async function handleToolCall(params: any) { | |
| }; | ||
| } | ||
|
|
||
| case "list_snippets": { | ||
| const args = ListSnippetsSchema.parse(params.arguments); | ||
| const { project_id, ...options } = args; | ||
| const snippets = await listSnippets(project_id, options); | ||
| return { | ||
| content: [{ type: "text", text: JSON.stringify(snippets, null, 2) }], | ||
| }; | ||
| } | ||
|
|
||
| case "get_snippet": { | ||
| const args = GetSnippetSchema.parse(params.arguments); | ||
| const snippet = await getSnippet(args.project_id, args.snippet_id); | ||
| const result: Record<string, unknown> = { ...snippet }; | ||
| if (args.include_content) { | ||
| const files = snippet.files ?? []; | ||
| if (files.length > 1) { | ||
| const firstFile = files[0]; | ||
| let ref: string; | ||
| if (args.ref !== undefined) { | ||
| ref = args.ref; | ||
| } else { | ||
| if (!firstFile.raw_url) throw new Error(`Snippet file "${firstFile.path}" has no raw_url`); | ||
| ref = extractSnippetRef(firstFile.raw_url, args.snippet_id, firstFile.path); | ||
| } | ||
| result.files = await Promise.all( | ||
| files.map(async f => ({ | ||
| ...f, | ||
| content: await getSnippetFileRawContent(args.project_id, args.snippet_id, ref, f.path), | ||
| })) | ||
| ); | ||
| } else { | ||
| result.content = await getSnippetRawContent( | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| args.project_id, | ||
| args.snippet_id | ||
| ); | ||
|
zereight marked this conversation as resolved.
|
||
| } | ||
| } | ||
| return { | ||
| content: [{ type: "text", text: JSON.stringify(result, null, 2) }], | ||
| }; | ||
| } | ||
|
|
||
| case "create_snippet": { | ||
| const args = CreateSnippetSchema.parse(params.arguments); | ||
| const { project_id, ...options } = args; | ||
| const snippet = await createSnippet(project_id, options); | ||
| return { | ||
| content: [{ type: "text", text: JSON.stringify(snippet, null, 2) }], | ||
| }; | ||
| } | ||
|
|
||
| case "update_snippet": { | ||
| const args = UpdateSnippetSchema.parse(params.arguments); | ||
| const { project_id, ...options } = args; | ||
| const snippet = await updateSnippet(project_id, options); | ||
| return { | ||
| content: [{ type: "text", text: JSON.stringify(snippet, null, 2) }], | ||
| }; | ||
| } | ||
|
|
||
| case "delete_snippet": { | ||
| const args = DeleteSnippetSchema.parse(params.arguments); | ||
| await deleteSnippet(args.project_id, args.snippet_id); | ||
| return { | ||
| content: [ | ||
| { | ||
| type: "text", | ||
| text: JSON.stringify( | ||
| { | ||
| status: "success", | ||
| message: `Snippet ${args.snippet_id} deleted successfully`, | ||
| }, | ||
| null, | ||
| 2 | ||
| ), | ||
| }, | ||
| ], | ||
| }; | ||
| } | ||
|
|
||
| case "list_webhooks": { | ||
| const args = ListWebhooksSchema.parse(params.arguments); | ||
| const webhooks = await listWebhooks(args); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.