This commit is contained in:
Shawn Morreau
2025-11-20 06:54:04 -05:00
27 changed files with 156950 additions and 218 deletions
-2
View File
@@ -1,2 +0,0 @@
# Mark generated files as linguist-generated to exclude from language statistics
*.js linguist-detectable=false
+1 -1
View File
@@ -8,5 +8,5 @@ if git diff --cached --name-only | grep -q "^package.json$"; then
pnpm build
# Add the built files and lockfile to the commit
git add entry.js mcp-server.js pnpm-lock.yaml
git add entry mcp-server pnpm-lock.yaml
fi
+1
View File
@@ -19,6 +19,7 @@ export const claude = agent({
process.env.ANTHROPIC_API_KEY = apiKey;
const prompt = addInstructions(payload);
console.log(prompt);
const queryInstance = query({
prompt,
+3 -1
View File
@@ -1,13 +1,15 @@
import type { AgentName } from "../external.ts";
import { claude } from "./claude.ts";
import { codex } from "./codex.ts";
import { cursor } from "./cursor.ts";
import { gemini } from "./gemini.ts";
import type { Agent } from "./shared.ts";
export const agents = {
claude,
codex,
cursor,
gemini,
} as const;
} satisfies Record<AgentName, Agent>;
export type AgentInputKey = (typeof agents)[keyof typeof agents]["inputKeys"][number];
+10 -6
View File
@@ -1,5 +1,5 @@
import type { Payload } from "../external.ts";
import { ghPullfrogMcpName } from "../mcp/index.ts";
import { ghPullfrogMcpName } from "../external.ts";
import { modes } from "../modes.ts";
export const addInstructions = (payload: Payload) =>
@@ -46,16 +46,20 @@ Ensure after your edits are done, your final comments do not contain intermediat
## Mode Selection
choose the appropriate mode based on the prompt payload:
Before starting any work, you must first determine which mode to use by examining the request and calling ${ghPullfrogMcpName}/select_mode.
Available modes:
${[...modes, ...payload.modes].map((w) => ` - "${w.name}": ${w.description}`).join("\n")}
## Modes
${[...modes, ...payload.modes].map((w) => `### ${w.name}\n\n${w.prompt}`).join("\n\n")}
**IMPORTANT**: The first thing you must do is:
1. Examine the user's request/prompt carefully
2. Determine which mode is most appropriate based on the mode descriptions above
3. Call ${ghPullfrogMcpName}/select_mode with the chosen mode name
4. The tool will return detailed instructions for that mode - follow those instructions exactly
************* USER PROMPT *************
${payload.prompt}
${JSON.stringify(payload.event, null, 2)}`;
${typeof payload.event === "string" ? payload.event : JSON.stringify(payload.event, null, 2)}`;
+3 -14
View File
@@ -1,7 +1,5 @@
import { spawnSync } from "node:child_process";
import { chmodSync, createWriteStream, existsSync } from "node:fs";
import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pipeline } from "node:stream/promises";
import type { McpStdioServerConfig } from "@anthropic-ai/claude-agent-sdk";
@@ -108,11 +106,7 @@ export async function installFromNpmTarball({
log.info(`📦 Installing ${packageName}@${resolvedVersion}...`);
// Derive temp directory prefix from package name (remove @, replace / with -, add trailing -)
const tempDirPrefix = packageName.replace("@", "").replace(/\//g, "-") + "-";
// Create temp directory
const tempDir = await mkdtemp(join(tmpdir(), tempDirPrefix));
const tempDir = process.env.PULLFROG_TEMP_DIR!;
const tarballPath = join(tempDir, "package.tgz");
// Download tarball from npm
@@ -279,12 +273,7 @@ export async function installFromCurl({
}: InstallFromCurlParams): Promise<string> {
log.info(`📦 Installing ${executableName}...`);
// Derive temp directory prefix from executable name (sanitize similar to package name)
// Replace any special characters with - and ensure trailing -
const tempDirPrefix = executableName.replace(/[^a-zA-Z0-9]/g, "-") + "-";
// Create temp directory
const tempDir = await mkdtemp(join(tmpdir(), tempDirPrefix));
const tempDir = process.env.PULLFROG_TEMP_DIR!;
const installScriptPath = join(tempDir, "install.sh");
// Download the install script
@@ -302,7 +291,7 @@ export async function installFromCurl({
// Make install script executable
chmodSync(installScriptPath, 0o755);
log.info("Installing to temp directory...");
log.info(`Installing to temp directory at ${tempDir}...`);
// Run the install script with HOME set to temp directory
// The Cursor install script installs to $HOME/.local/bin/{executableName}
Executable
+48355
View File
File diff suppressed because one or more lines are too long
+39 -4
View File
@@ -1,5 +1,39 @@
import { build } from "esbuild";
// @ts-check
import { build } from "esbuild";
import { readFileSync, writeFileSync } from "fs";
// Plugin to strip shebangs from output files
/**
* @type {import("esbuild").Plugin}
*/
const stripShebangPlugin = {
name: "strip-shebang",
setup(build) {
build.onEnd((result) => {
if (result.errors.length > 0) return;
// Strip shebang from the output file
const outputFile = build.initialOptions.outfile;
if (outputFile) {
try {
const content = readFileSync(outputFile, "utf8");
// Remove shebang line from the beginning if present
const withoutShebang = content.startsWith("#!")
? content.slice(content.indexOf("\n") + 1)
: content;
writeFileSync(outputFile, withoutShebang);
} catch (error) {
// File might not exist, ignore
}
}
});
},
};
/**
* @type {import("esbuild").BuildOptions}
*/
const sharedConfig = {
bundle: true,
format: "esm",
@@ -29,15 +63,16 @@ const sharedConfig = {
await build({
...sharedConfig,
entryPoints: ["./entry.ts"],
outfile: "./entry.js",
outfile: "./entry",
plugins: [stripShebangPlugin],
});
// Build the MCP server bundle
await build({
...sharedConfig,
entryPoints: ["./mcp/server.ts"],
outfile: "./mcp-server.js",
outfile: "./mcp-server",
plugins: [stripShebangPlugin],
});
console.log("✅ Build completed successfully!");
+35 -2
View File
@@ -1,6 +1,38 @@
import type { AgentName } from "./main.ts";
/**
* ⚠️ NO IMPORTS except modes.ts - this file is imported by Next.js and must avoid pulling in backend code.
* All shared constants, types, and data used by both the Next.js app and the action runtime live here.
* Other files in action/ re-export from this file for backward compatibility.
*/
import type { Mode } from "./modes.ts";
// mcp name constant
export const ghPullfrogMcpName = "gh-pullfrog";
// agent manifest - static metadata about available agents
export const agentsManifest = {
claude: {
name: "Claude Code",
apiKeys: ["anthropic_api_key"],
},
codex: {
name: "Codex CLI",
apiKeys: ["openai_api_key"],
},
cursor: {
name: "Cursor CLI",
apiKeys: ["cursor_api_key"],
},
gemini: {
name: "Gemini CLI",
apiKeys: ["google_api_key", "gemini_api_key"],
},
} as const;
// agent name type - union of agent slugs
export type AgentName = keyof typeof agentsManifest;
// payload type for agent execution
export type Payload = {
"~pullfrog": true;
@@ -16,8 +48,9 @@ export type Payload = {
/**
* Event data from webhook payload.
* Can be an object (will be JSON.stringify'd) or a string (used as-is).
*/
readonly event: object;
readonly event: object | string;
/**
* Execution mode configuration
+185 -95
View File
@@ -1,7 +1,11 @@
import { existsSync, readFileSync } from "node:fs";
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { flatMorph } from "@ark/util";
import { type } from "arktype";
import { agents } from "./agents/index.ts";
import type { Payload } from "./external.ts";
import type { AgentName as AgentNameType, Payload } from "./external.ts";
import { createMcpConfigs } from "./mcp/config.ts";
import { modes } from "./modes.ts";
import packageJson from "./package.json" with { type: "json" };
@@ -15,8 +19,9 @@ import {
} from "./utils/github.ts";
import { setupGitAuth, setupGitConfig } from "./utils/setup.ts";
// runtime validation using agents (needed for ArkType)
// Note: The AgentName type is defined in external.ts, this is the runtime validator
export const AgentName = type.enumerated(...Object.values(agents).map((agent) => agent.name));
export type AgentName = typeof AgentName.infer;
export const AgentInputKey = type.enumerated(
...Object.values(agents).flatMap((agent) => agent.inputKeys)
@@ -30,7 +35,7 @@ const keyInputDefs = flatMorph(agents, (_, agent) =>
export const Inputs = type({
prompt: "string",
...keyInputDefs,
"agent?": AgentName.or("undefined"),
"agent?": type.enumerated(...Object.values(agents).map((agent) => agent.name)).or("undefined"),
});
export type Inputs = typeof Inputs.infer;
@@ -41,6 +46,36 @@ export interface MainResult {
error?: string | undefined;
}
export async function main(inputs: Inputs): Promise<MainResult> {
const partialCtx = await initializeContext(inputs);
const ctx = partialCtx as MainContext;
try {
await determineAgent(ctx);
setupGitAuth(ctx.githubInstallationToken, ctx.repoContext);
await setupTempDirectory(ctx);
setupMcpLogPolling(ctx);
ctx.payload = parsePayload(inputs);
setupMcpServers(ctx);
await installAgentCli(ctx);
validateApiKey(ctx);
const result = await runAgent(ctx);
return await handleAgentResult(result);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
log.error(errorMessage);
await log.writeSummary();
return {
success: false,
error: errorMessage,
};
} finally {
await cleanup(partialCtx);
}
}
/**
* Throw an error for missing API key with helpful message linking to repo settings
*/
@@ -90,110 +125,165 @@ To fix this, add the required secret to your GitHub repository:
throw new Error(message);
}
export async function main(inputs: Inputs): Promise<MainResult> {
let tokenToRevoke: string | null = null;
interface MainContext {
inputs: Inputs;
githubInstallationToken: string;
tokenToRevoke: string | null;
repoContext: RepoContext;
agentName: AgentNameType;
agent: (typeof agents)[AgentNameType];
sharedTempDir: string;
mcpLogPath: string;
pollInterval: NodeJS.Timeout | null;
payload: Payload;
mcpServers: ReturnType<typeof createMcpConfigs>;
cliPath: string;
apiKey: string;
}
try {
log.info(`🐸 Running pullfrog/action@${packageJson.version}...`);
async function initializeContext(
inputs: Inputs
): Promise<Omit<MainContext, "payload" | "mcpServers" | "cliPath" | "apiKey">> {
log.info(`🐸 Running pullfrog/action@${packageJson.version}...`);
Inputs.assert(inputs);
setupGitConfig();
Inputs.assert(inputs);
setupGitConfig();
const { githubInstallationToken, wasAcquired } = await setupGitHubInstallationToken();
const tokenToRevoke = wasAcquired ? githubInstallationToken : null;
const repoContext = parseRepoContext();
const { githubInstallationToken, wasAcquired } = await setupGitHubInstallationToken();
if (wasAcquired) {
tokenToRevoke = githubInstallationToken;
}
const repoContext = parseRepoContext();
return {
inputs,
githubInstallationToken,
tokenToRevoke,
repoContext,
agentName: "claude" as AgentNameType,
agent: agents.claude,
sharedTempDir: "",
mcpLogPath: "",
pollInterval: null,
};
}
const repoSettings = await fetchRepoSettings({
token: githubInstallationToken,
repoContext,
});
async function determineAgent(
ctx: Omit<MainContext, "payload" | "mcpServers" | "cliPath" | "apiKey">
): Promise<void> {
const repoSettings = await fetchRepoSettings({
token: ctx.githubInstallationToken,
repoContext: ctx.repoContext,
});
const agentName: AgentName = inputs.agent || repoSettings.defaultAgent || "claude";
ctx.agentName = ctx.inputs.agent || repoSettings.defaultAgent || "claude";
ctx.agent = agents[ctx.agentName];
}
const agent = agents[agentName];
async function setupTempDirectory(
ctx: Omit<MainContext, "payload" | "mcpServers" | "cliPath" | "apiKey">
): Promise<void> {
ctx.sharedTempDir = await mkdtemp(join(tmpdir(), "pullfrog-"));
process.env.PULLFROG_TEMP_DIR = ctx.sharedTempDir;
ctx.mcpLogPath = join(ctx.sharedTempDir, "mcpLog.txt");
await writeFile(ctx.mcpLogPath, "", "utf-8");
log.info(`📂 PULLFROG_TEMP_DIR has been created at ${ctx.sharedTempDir}`);
}
setupGitAuth(githubInstallationToken, repoContext);
const mcpServers = createMcpConfigs(githubInstallationToken);
log.debug(`📋 MCP Config: ${JSON.stringify(mcpServers, null, 2)}`);
// Install agent CLI before running
const cliPath = await agent.install();
log.info(`Running ${agentName}...`);
let payload: Payload;
try {
// attempt JSON parsing
const parsedPrompt = JSON.parse(inputs.prompt);
if (!("~pullfrog" in parsedPrompt)) {
// is non-pullfrog JSON (probably from a GitHub event), treat it as a plain text prompt
throw new Error();
function setupMcpLogPolling(ctx: MainContext): void {
let lastSize = 0;
ctx.pollInterval = setInterval(() => {
if (existsSync(ctx.mcpLogPath)) {
const content = readFileSync(ctx.mcpLogPath, "utf-8");
if (content.length > lastSize) {
const newContent = content.slice(lastSize);
process.stdout.write(newContent);
lastSize = content.length;
}
payload = parsedPrompt as Payload;
} catch {
payload = {
"~pullfrog": true,
agent: null,
prompt: inputs.prompt,
event: {},
modes,
};
}
}, 100);
}
log.box(payload.prompt, { title: "Prompt" });
const matchingInputKey = agent.inputKeys.find((inputKey) => inputs[inputKey]);
if (!matchingInputKey) {
throwMissingApiKeyError({
agentName,
inputKeys: agent.inputKeys,
repoContext,
inputs,
});
function parsePayload(inputs: Inputs): Payload {
try {
const parsedPrompt = JSON.parse(inputs.prompt);
if (!("~pullfrog" in parsedPrompt)) {
throw new Error();
}
const apiKey = inputs[matchingInputKey]!;
const result = await agent.run({
payload,
mcpServers,
githubInstallationToken,
apiKey,
cliPath,
});
if (!result.success) {
return {
success: false,
error: result.error || "Agent execution failed",
output: result.output!,
};
}
log.success("Task complete.");
await log.writeSummary();
return parsedPrompt as Payload;
} catch {
return {
success: true,
output: result.output || "",
"~pullfrog": true,
agent: null,
prompt: inputs.prompt,
event: {},
modes,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
log.error(errorMessage);
await log.writeSummary();
return {
success: false,
error: errorMessage,
};
} finally {
if (tokenToRevoke) {
await revokeInstallationToken(tokenToRevoke);
}
}
}
function setupMcpServers(ctx: MainContext): void {
const allModes = [...modes, ...(ctx.payload.modes || [])];
ctx.mcpServers = createMcpConfigs(ctx.githubInstallationToken, allModes);
log.debug(`📋 MCP Config: ${JSON.stringify(ctx.mcpServers, null, 2)}`);
}
async function installAgentCli(ctx: MainContext): Promise<void> {
ctx.cliPath = await ctx.agent.install();
}
function validateApiKey(ctx: MainContext): void {
const matchingInputKey = ctx.agent.inputKeys.find(
(inputKey: string) => ctx.inputs[inputKey as AgentInputKey]
);
if (!matchingInputKey) {
throwMissingApiKeyError({
agentName: ctx.agentName,
inputKeys: ctx.agent.inputKeys,
repoContext: ctx.repoContext,
inputs: ctx.inputs,
});
}
ctx.apiKey = ctx.inputs[matchingInputKey as AgentInputKey]!;
}
async function runAgent(ctx: MainContext): Promise<import("./agents/shared.ts").AgentResult> {
log.info(`Running ${ctx.agentName}...`);
log.box(ctx.payload.prompt, { title: "Prompt" });
return ctx.agent.run({
payload: ctx.payload,
mcpServers: ctx.mcpServers,
githubInstallationToken: ctx.githubInstallationToken,
apiKey: ctx.apiKey,
cliPath: ctx.cliPath,
});
}
async function handleAgentResult(
result: import("./agents/shared.ts").AgentResult
): Promise<MainResult> {
if (!result.success) {
return {
success: false,
error: result.error || "Agent execution failed",
output: result.output!,
};
}
log.success("Task complete.");
await log.writeSummary();
return {
success: true,
output: result.output || "",
};
}
async function cleanup(
ctx: Omit<MainContext, "payload" | "mcpServers" | "cliPath" | "apiKey">
): Promise<void> {
if (ctx.pollInterval) {
clearInterval(ctx.pollInterval);
}
if (ctx.tokenToRevoke) {
await revokeInstallationToken(ctx.tokenToRevoke);
}
}
Executable
+107749
View File
File diff suppressed because one or more lines are too long
+92
View File
@@ -0,0 +1,92 @@
# gh-pullfrog MCP Tools
this directory contains the mcp (model context protocol) server tools for interacting with github.
## available tools
### check suite tools
#### `get_check_suite_logs`
get workflow run logs for a failed check suite.
**parameters:**
- `check_suite_id` (number): the id from check_suite.id in the webhook payload
**replaces:** `gh run list` and `gh run view --log`
**returns:**
all logs from all failed workflow runs in the check suite, including:
- workflow run details (id, name, html_url, conclusion)
- job details for each workflow run (id, name, status, conclusion, logs)
**example:**
```typescript
// when handling a check_suite_completed webhook
await mcp.call("gh-pullfrog/get_check_suite_logs", {
check_suite_id: check_suite.id
});
```
### review tools
#### `get_review_comments`
get all line-by-line comments for a specific pull request review.
**parameters:**
- `pull_number` (number): the pull request number
- `review_id` (number): the id from review.id in the webhook payload
**replaces:** `gh api repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments`
**returns:**
array of review comments including:
- file path, line number, comment body
- side (LEFT/RIGHT) and position in diff
- user, timestamps, html_url
- in_reply_to_id for threaded comments
**example:**
```typescript
// when handling a pull_request_review_submitted webhook
await mcp.call("gh-pullfrog/get_review_comments", {
pull_number: 47,
review_id: review.id
});
```
#### `list_pull_request_reviews`
list all reviews for a pull request.
**parameters:**
- `pull_number` (number): the pull request number
**replaces:** `gh api repos/{owner}/{repo}/pulls/{pull_number}/reviews`
**returns:**
array of reviews with:
- review id, body, state (approved/changes_requested/commented)
- user, commit_id, submitted_at, html_url
**example:**
```typescript
await mcp.call("gh-pullfrog/list_pull_request_reviews", {
pull_number: 47
});
```
### other tools
see individual files for documentation on other tools:
- `comment.ts` - create, edit, and update comments
- `issue.ts` - create issues
- `pr.ts` - create pull requests
- `prInfo.ts` - get pull request information
- `review.ts` - create pull request reviews
- `selectMode.ts` - select execution mode
## usage in agents
agents should never use the `gh` cli. instead, they should use the mcp tools provided by this server.
the agent instructions automatically include guidance on using these tools.
+94
View File
@@ -0,0 +1,94 @@
import { type } from "arktype";
import { contextualize, tool } from "./shared.ts";
export const GetCheckSuiteLogs = type({
check_suite_id: type.number.describe("the id from check_suite.id"),
});
export const GetCheckSuiteLogsTool = tool({
name: "get_check_suite_logs",
description:
"get workflow run logs for a failed check suite. pass check_suite.id from the webhook payload.",
parameters: GetCheckSuiteLogs,
execute: contextualize(async ({ check_suite_id }, ctx) => {
// get workflow runs for this specific check suite
const workflowRuns = await ctx.octokit.paginate(
ctx.octokit.rest.actions.listWorkflowRunsForRepo,
{
owner: ctx.owner,
repo: ctx.name,
check_suite_id,
per_page: 100,
}
);
const failedRuns = workflowRuns.filter((run) => run.conclusion === "failure");
if (failedRuns.length === 0) {
return {
check_suite_id,
message: "no failed workflow runs found for this check suite",
workflow_runs: [],
};
}
// get logs for each failed run
const logsForRuns = await Promise.all(
failedRuns.map(async (run) => {
const jobs = await ctx.octokit.paginate(ctx.octokit.rest.actions.listJobsForWorkflowRun, {
owner: ctx.owner,
repo: ctx.name,
run_id: run.id,
});
const jobLogs = await Promise.all(
jobs.map(async (job) => {
try {
const logsResponse = await ctx.octokit.rest.actions.downloadJobLogsForWorkflowRun({
owner: ctx.owner,
repo: ctx.name,
job_id: job.id,
});
const logsUrl = logsResponse.url;
const logsText = await fetch(logsUrl).then((r) => r.text());
return {
job_id: job.id,
job_name: job.name,
status: job.status,
conclusion: job.conclusion,
started_at: job.started_at,
completed_at: job.completed_at,
logs: logsText,
};
} catch (error) {
return {
job_id: job.id,
job_name: job.name,
status: job.status,
conclusion: job.conclusion,
started_at: job.started_at,
completed_at: job.completed_at,
error: `failed to fetch logs: ${error}`,
};
}
})
);
return {
workflow_run_id: run.id,
workflow_name: run.name,
html_url: run.html_url,
conclusion: run.conclusion,
jobs: jobLogs,
};
})
);
return {
check_suite_id,
workflow_runs: logsForRuns,
};
}),
});
+1 -1
View File
@@ -77,7 +77,7 @@ export const CreateWorkingCommentTool = tool({
owner: ctx.owner,
repo: ctx.name,
issue_number: issueNumber,
body: intent,
body: `${intent} <img src="https://pullfrog.ai/party-parrot.gif" width="14px" height="14px" style="vertical-align: middle; margin-left: 4px;" />`,
});
workingCommentId = result.data.id;
+7 -24
View File
@@ -2,23 +2,23 @@
* Simple MCP configuration helper for adding our minimal GitHub comment server
*/
import type { McpServerConfig, McpStdioServerConfig } from "@anthropic-ai/claude-agent-sdk";
import type { McpStdioServerConfig } from "@anthropic-ai/claude-agent-sdk";
import { fromHere } from "@ark/fs";
import { log } from "../utils/cli.ts";
import { ghPullfrogMcpName } from "../external.ts";
import type { Mode } from "../modes.ts";
import { parseRepoContext } from "../utils/github.ts";
import { ghPullfrogMcpName } from "./index.ts";
export type McpName = typeof ghPullfrogMcpName;
export type McpConfigs = Record<McpName, McpStdioServerConfig>;
export function createMcpConfigs(githubInstallationToken: string): McpConfigs {
export function createMcpConfigs(githubInstallationToken: string, modes: Mode[]): McpConfigs {
const repoContext = parseRepoContext();
const githubRepository = `${repoContext.owner}/${repoContext.name}`;
// In production (GitHub Actions), mcp-server.js is in same directory as entry.js (where this is bundled)
// In production (GitHub Actions), mcp-server is in same directory as entry.js (where this is bundled)
// In development, server.ts is in the same directory as this file (config.ts)
const serverPath = process.env.GITHUB_ACTIONS ? fromHere("mcp-server.js") : fromHere("server.ts");
const serverPath = process.env.GITHUB_ACTIONS ? fromHere("mcp-server") : fromHere("server.ts");
return {
[ghPullfrogMcpName]: {
@@ -27,25 +27,8 @@ export function createMcpConfigs(githubInstallationToken: string): McpConfigs {
env: {
GITHUB_INSTALLATION_TOKEN: githubInstallationToken,
GITHUB_REPOSITORY: githubRepository,
PULLFROG_MODES: JSON.stringify(modes),
},
},
};
}
/**
* Iterate through MCP servers and call the provided handler for each stdio server
* Shared logic to avoid duplication across agents
*/
export function forEachStdioMcpServer(
mcpServers: Record<string, McpServerConfig>,
handler: (serverName: string, serverConfig: McpStdioServerConfig) => void
): void {
for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
// Only configure stdio servers (CLIs support stdio MCP servers)
if (!("command" in serverConfig)) {
log.warning(`MCP server '${serverName}' is not a stdio server, skipping...`);
continue;
}
handler(serverName, serverConfig);
}
}
+43
View File
@@ -0,0 +1,43 @@
import { execSync } from "node:child_process";
import { type } from "arktype";
import { contextualize, tool } from "./shared.ts";
export const ListFiles = type({
path: type.string
.describe("The path to list files from (defaults to current directory)")
.default("."),
});
export const ListFilesTool = tool({
name: "list_files",
description:
"List files in the repository using git ls-files. Useful for discovering the file structure and locating files.",
parameters: ListFiles,
execute: contextualize(async ({ path }) => {
try {
// Use git ls-files to list tracked files
// This respects .gitignore and gives a clean list of source files
const command = path === "." ? "git ls-files" : `git ls-files ${path}`;
const output = execSync(command, { encoding: "utf-8" });
const files = output.split("\n").filter((f) => f.trim() !== "");
if (files.length === 0) {
// Fallback for non-git environments or untracked files
const findCmd = `find ${path} -maxdepth 3 -not -path '*/.*' -type f`;
const findOutput = execSync(findCmd, { encoding: "utf-8" });
return {
files: findOutput.split("\n").filter((f) => f.trim() !== ""),
method: "find",
};
}
return { files, method: "git" };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
error: `Failed to list files: ${errorMessage}`,
hint: "Try using a specific path if the repository root is not the current directory.",
};
}
}),
});
+2 -4
View File
@@ -1,4 +1,2 @@
// for reasos this can't live alongide config.ts
// because its imported into the frontend UI
// and we don't want to pull in FastMCP, etc
export const ghPullfrogMcpName = "gh-pullfrog";
// re-export from external.ts for backward compatibility
export { ghPullfrogMcpName } from "../external.ts";
+2 -1
View File
@@ -36,7 +36,8 @@ export const PullRequestInfoTool = tool({
execSync(`git fetch origin ${headBranch}`, { stdio: "inherit" });
log.info(`Checking out PR branch: origin/${headBranch}`);
execSync(`git checkout origin/${headBranch}`, { stdio: "inherit" });
// check out a local branch tracking the remote branch so we can push changes
execSync(`git checkout -B ${headBranch} origin/${headBranch}`, { stdio: "inherit" });
return {
number: data.number,
+76
View File
@@ -0,0 +1,76 @@
import { type } from "arktype";
import { contextualize, tool } from "./shared.ts";
export const GetReviewComments = type({
pull_number: type.number.describe("The pull request number"),
review_id: type.number.describe("The review ID to get comments for"),
});
export const GetReviewCommentsTool = tool({
name: "get_review_comments",
description:
"Get all review comments for a specific pull request review. Returns line-by-line comments that were left on specific code locations.",
parameters: GetReviewComments,
execute: contextualize(async ({ pull_number, review_id }, ctx) => {
const comments = await ctx.octokit.paginate(ctx.octokit.rest.pulls.listCommentsForReview, {
owner: ctx.owner,
repo: ctx.name,
pull_number,
review_id,
});
return {
review_id,
pull_number,
comments: comments.map((comment) => ({
id: comment.id,
body: comment.body,
path: comment.path,
line: comment.line,
side: comment.side,
start_line: comment.start_line,
start_side: comment.start_side,
user: typeof comment.user === "string" ? comment.user : comment.user?.login,
created_at: comment.created_at,
updated_at: comment.updated_at,
html_url: comment.html_url,
in_reply_to_id: comment.in_reply_to_id,
diff_hunk: comment.diff_hunk,
reactions: comment.reactions,
})),
count: comments.length,
};
}),
});
export const ListPullRequestReviews = type({
pull_number: type.number.describe("The pull request number to list reviews for"),
});
export const ListPullRequestReviewsTool = tool({
name: "list_pull_request_reviews",
description:
"List all reviews for a pull request. Returns all reviews including approvals, request changes, and comments.",
parameters: ListPullRequestReviews,
execute: contextualize(async ({ pull_number }, ctx) => {
const reviews = await ctx.octokit.paginate(ctx.octokit.rest.pulls.listReviews, {
owner: ctx.owner,
repo: ctx.name,
pull_number,
});
return {
pull_number,
reviews: reviews.map((review) => ({
id: review.id,
body: review.body,
state: review.state,
user: review.user?.login,
commit_id: review.commit_id,
submitted_at: review.submitted_at,
html_url: review.html_url,
})),
count: reviews.length,
};
}),
});
+55
View File
@@ -0,0 +1,55 @@
import { type } from "arktype";
import type { Mode } from "../modes.ts";
import { contextualize, tool } from "./shared.ts";
// Get modes from environment variable (set by createMcpConfigs)
function getModes(): Mode[] {
const modesJson = process.env.PULLFROG_MODES;
if (modesJson) {
try {
return JSON.parse(modesJson);
} catch {
return [];
}
}
return [];
}
export const SelectMode = type({
modeName: type.string.describe(
"the name of the mode to select (e.g., 'Plan', 'Build', 'Review', 'Prompt')"
),
});
export const SelectModeTool = tool({
name: "select_mode",
description:
"Select a mode and get its detailed prompt instructions. Call this first to determine which mode to use based on the request.",
parameters: SelectMode,
execute: contextualize(async ({ modeName }) => {
const allModes = getModes();
if (allModes.length === 0) {
return {
error:
"No modes available. Modes must be provided via PULLFROG_MODES environment variable.",
};
}
const selectedMode = allModes.find((m) => m.name.toLowerCase() === modeName.toLowerCase());
if (!selectedMode) {
const availableModes = allModes.map((m) => m.name).join(", ");
return {
error: `Mode "${modeName}" not found. Available modes: ${availableModes}`,
availableModes: allModes.map((m) => ({ name: m.name, description: m.description })),
};
}
return {
modeName: selectedMode.name,
description: selectedMode.description,
prompt: selectedMode.prompt,
};
}),
});
+9 -2
View File
@@ -1,16 +1,18 @@
#!/usr/bin/env node
// Minimal GitHub Issue Comment MCP Server
import { FastMCP } from "fastmcp";
import { GetCheckSuiteLogsTool } from "./checkSuite.ts";
import {
CreateCommentTool,
CreateWorkingCommentTool,
EditCommentTool,
UpdateWorkingCommentTool,
} from "./comment.ts";
// import { ListFilesTool } from "./files.ts";
import { IssueTool } from "./issue.ts";
import { PullRequestTool } from "./pr.ts";
import { PullRequestInfoTool } from "./prInfo.ts";
import { ReviewTool } from "./review.ts";
import { GetReviewCommentsTool, ListPullRequestReviewsTool } from "./reviewComments.ts";
import { SelectModeTool } from "./selectMode.ts";
import { addTools } from "./shared.ts";
const server = new FastMCP({
@@ -19,14 +21,19 @@ const server = new FastMCP({
});
addTools(server, [
SelectModeTool,
CreateCommentTool,
EditCommentTool,
CreateWorkingCommentTool,
UpdateWorkingCommentTool,
IssueTool,
// ListFilesTool,
PullRequestTool,
ReviewTool,
PullRequestInfoTool,
GetReviewCommentsTool,
ListPullRequestReviewsTool,
GetCheckSuiteLogsTool,
]);
server.start();
+15 -48
View File
@@ -1,9 +1,8 @@
import { appendFileSync } from "node:fs";
import { join } from "node:path";
import { cached } from "@ark/util";
import { Octokit } from "@octokit/rest";
import type { StandardSchemaV1 } from "@standard-schema/spec";
import type { FastMCP, Tool } from "fastmcp";
import { log } from "../utils/cli.ts";
import { parseRepoContext, type RepoContext } from "../utils/github.ts";
export interface ToolResult {
@@ -32,49 +31,6 @@ export interface McpContext extends RepoContext {
octokit: Octokit;
}
/**
* Get the log file path
*/
function getLogPath(): string {
return join(process.cwd(), "log.txt");
}
/**
* Log MCP tool call information to log.txt
*/
function logToolCall({
toolName,
request,
error,
success,
}: {
toolName: string;
request: unknown;
error?: unknown;
success?: boolean;
}) {
const logPath = getLogPath();
const timestamp = new Date().toISOString();
const requestStr = JSON.stringify(request, null, 2);
let logEntry = `[${timestamp}] Tool: ${toolName}\nRequest: ${requestStr}\n`;
if (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
const errorStack = error instanceof Error ? error.stack : undefined;
logEntry += `Error: ${errorMessage}\n`;
if (errorStack) {
logEntry += `Stack: ${errorStack}\n`;
}
logEntry += `Status: FAILED\n`;
} else if (success !== undefined) {
logEntry += `Status: ${success ? "SUCCESS" : "FAILED"}\n`;
}
logEntry += `${"=".repeat(80)}\n\n`;
appendFileSync(logPath, logEntry, "utf-8");
}
export const tool = <const params>(toolDef: Tool<any, StandardSchemaV1<params>>) => {
// Wrap the execute function to add logging with the tool name
const toolName = toolDef.name;
@@ -82,15 +38,26 @@ export const tool = <const params>(toolDef: Tool<any, StandardSchemaV1<params>>)
toolDef.execute = async (args: params, context: any) => {
try {
logToolCall({ toolName, request: args });
const result = await originalExecute(args, context);
// Check if result is a ToolResult with isError property
const isError =
result && typeof result === "object" && "isError" in result && result.isError === true;
logToolCall({ toolName, request: args, success: !isError });
const resultData =
result && typeof result === "object" && "content" in result
? (result as ToolResult).content[0]?.text
: undefined;
if (isError && resultData) {
log.toolCall({ toolName, request: args, error: resultData });
} else if (resultData) {
log.toolCall({ toolName, request: args, result: resultData });
} else {
log.toolCall({ toolName, request: args });
}
return result;
} catch (error) {
logToolCall({ toolName, request: args, error });
const errorMessage = error instanceof Error ? error.message : String(error);
log.toolCall({ toolName, request: args, error: errorMessage });
throw error;
}
};
+10 -5
View File
@@ -1,4 +1,4 @@
import { ghPullfrogMcpName } from "./mcp/index.ts";
import { ghPullfrogMcpName } from "./external.ts";
export interface Mode {
name: string;
@@ -6,13 +6,16 @@ export interface Mode {
prompt: string;
}
const initialCommentInstruction = `Use ${ghPullfrogMcpName}/create_working_comment to create an initial Working Comment with a conversational description of what work you are about to perform.`;
export const modes: Mode[] = [
{
name: "Plan",
description:
"Create plans, break down tasks, outline steps, analyze requirements, understand scope of work, or provide task breakdowns",
prompt: `Follow these steps:
1. Create initial response comment using ${ghPullfrogMcpName}/create_working_comment saying "I'll {summary of request}"
1. ${initialCommentInstruction}
2. If the request requires understanding the codebase structure, dependencies, or conventions, gather relevant context (read AGENTS.md if it exists, understand how to install dependencies, run tests, run builds, and make changes according to best practices). Skip this step if the prompt is trivial and self-contained.
3. Analyze the request and break it down into clear, actionable tasks
4. Consider dependencies, potential challenges, and implementation order
@@ -25,7 +28,7 @@ export const modes: Mode[] = [
description:
"Implement, build, create, or develop code changes; make specific changes to files or features; execute a plan; or handle tasks with specific implementation details",
prompt: `Follow these steps:
1. Create initial response comment using ${ghPullfrogMcpName}/create_working_comment saying "I'll {summary of request}"
1. ${initialCommentInstruction}
2. If the request requires understanding the codebase structure, dependencies, or conventions, gather relevant context (read AGENTS.md if it exists, understand how to install dependencies, run tests, run builds, and make changes according to best practices). Skip this step if the prompt is trivial and self-contained.
3. Understand the requirements and any existing plan
4. Make the necessary code changes
@@ -38,7 +41,8 @@ export const modes: Mode[] = [
description:
"Review code, PRs, or implementations; provide feedback or suggestions; identify issues; or check code quality, style, and correctness",
prompt: `Follow these steps:
1. Create initial response comment using ${ghPullfrogMcpName}/create_working_comment saying "I'll review this"
1. ${initialCommentInstruction}
2. Get PR info with ${ghPullfrogMcpName}/get_pull_request (this automatically prepares the repository by fetching and checking out the PR branch)
3. View diff: git diff origin/<base>...origin/<head> (use line numbers from this for inline comments, replace <base> and <head> with 'base' and 'head' from PR info)
4. Read files from the checked-out PR branch to understand the implementation
@@ -52,7 +56,8 @@ export const modes: Mode[] = [
description:
"Fallback for tasks that don't fit other workflows, direct prompts via comments, or requests requiring general assistance without a specific workflow pattern",
prompt: `Follow these steps:
1. Create an initial "Working Comment" using ${ghPullfrogMcpName}/create_working_comment saying "I'll {summary of request}"
1. ${initialCommentInstruction}
2. Perform the requested task. Only take action if you have high confidence that you understand what is being asked. If you are not sure, ask for clarification. Take stock of the tools at your disposal.
3. As your work progresses, update your Working Comment to share progress and results using ${ghPullfrogMcpName}/update_working_comment. Do not create additional comments unless you are explicitly asked to do so.
4. When you finish the task, update the Working Comment a final time with a summary of the results and links to any created issues, PRs, etc.`,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@pullfrog/action",
"version": "0.0.106",
"version": "0.0.110",
"type": "module",
"files": [
"index.js",
+4 -4
View File
@@ -3,13 +3,10 @@
[] gemini installation speed (bundle/esm.sh?) (TODO: SHAWN)
[] handle defaulting agent name value (TODO: SHAWN)
[] split up prompts, load dynamically based on mode
[] log.txt to stdout
[] entry.js
[] test agent/mode combinations
[] test if home directory mcp.json works if mcp.json is specified in repo
[] add footer to the working comment ("executed by {agent}", link to pullfrog (homepage) w/ small logo?, feedback (create github issue), link to workflow run)- see https://github.com/colinhacks/zod/issues/5459#issuecomment-3548382991
[] avoid passing all of process.env into agents: minimum # of vars
## MAYBE
@@ -33,3 +30,6 @@
[x] handle progressive comment updating from pullfrog mcp
[x] jules/gemini support
[x] standardize mcp server
[x] entry.js
[x] split up prompts, load dynamically based on mode
[x] log.txt to stdout
+1 -1
View File
@@ -1,4 +1,4 @@
import type { AgentName } from "../main.ts";
import type { AgentName } from "../external.ts";
import { log } from "./cli.ts";
import type { RepoContext } from "./github.ts";
+157 -2
View File
@@ -2,9 +2,11 @@
* CLI output utilities that work well in both local and GitHub Actions environments
*/
import { spawnSync } from "node:child_process";
import { appendFileSync, existsSync } from "node:fs";
import { join } from "node:path";
import * as core from "@actions/core";
import { spawnSync } from "child_process";
import { existsSync } from "fs";
import { table } from "table";
const isGitHubActions = !!process.env.GITHUB_ACTIONS;
const isDebugEnabled = process.env.LOG_LEVEL === "debug";
@@ -159,6 +161,43 @@ async function summaryTable(
core.info(`\n${tableText}\n`);
}
/**
* Print a formatted table using the table package
* Also logs to console and GitHub Actions summary
*/
async function printTable(
rows: Array<Array<{ data: string; header?: boolean } | string>>,
options?: {
title?: string;
}
): Promise<void> {
const { title } = options || {};
// Convert rows to string arrays for the table package
const tableData = rows.map((row) =>
row.map((cell) => {
if (typeof cell === "string") {
return cell;
}
return cell.data;
})
);
const formatted = table(tableData);
if (title) {
core.info(`\n${title}`);
}
core.info(`\n${formatted}\n`);
if (isGitHubActions) {
if (title) {
core.summary.addRaw(`**${title}**\n\n`);
}
core.summary.addRaw(`\`\`\`\n${formatted}\n\`\`\`\n`);
}
}
/**
* Print a separator line
*/
@@ -239,6 +278,11 @@ export const log = {
*/
summaryTable,
/**
* Print a formatted table using the table package
*/
table: printTable,
/**
* Print a separator line
*/
@@ -263,8 +307,119 @@ export const log = {
* End a collapsed group
*/
endGroup,
/**
* Log MCP tool call information to mcpLog.txt in the temp directory
*/
toolCall: ({
toolName,
request,
result,
error,
}: {
toolName: string;
request: unknown;
result?: string;
error?: string;
}): void => {
const logPath = getMcpLogPath();
const params: Parameters<typeof formatToolCall>[0] = { toolName, request };
if (error) {
params.error = error;
} else if (result) {
params.result = result;
}
const logEntry = formatToolCall(params);
appendFileSync(logPath, logEntry, "utf-8");
},
};
/**
* Get the path to the MCP log file in the temp directory
*/
function getMcpLogPath(): string {
const tempDir = process.env.PULLFROG_TEMP_DIR!;
return join(tempDir, "mcpLog.txt");
}
/**
* Format a value as JSON, using compact format for simple values and pretty-printed for complex ones
*/
function formatJsonValue(value: unknown): string {
const compact = JSON.stringify(value);
return compact.length > 80 || compact.includes("\n") ? JSON.stringify(value, null, 2) : compact;
}
/**
* Format a multi-line string with proper indentation for tool call output
* First line has the label, subsequent lines are indented 4 spaces
*/
function formatIndentedField(label: string, content: string): string {
if (!content.includes("\n")) {
return ` ${label}: ${content}\n`;
}
const lines = content.split("\n");
let formatted = ` ${label}: ${lines[0]}\n`;
for (let i = 1; i < lines.length; i++) {
formatted += ` ${lines[i]}\n`;
}
return formatted;
}
/**
* Format the input field for a tool call
*/
function formatToolInput(request: unknown): string {
const requestFormatted = formatJsonValue(request);
if (requestFormatted === "{}") {
return "";
}
return formatIndentedField("input", requestFormatted);
}
/**
* Format the result field for a tool call, parsing JSON if possible
*/
function formatToolResult(result: string): string {
try {
const parsed = JSON.parse(result);
const formatted = formatJsonValue(parsed);
return formatIndentedField("result", formatted);
} catch {
// Not JSON, display as-is
return formatIndentedField("result", result);
}
}
/**
* Format a complete tool call entry with tool name, input, result, and error
*/
function formatToolCall({
toolName,
request,
result,
error,
}: {
toolName: string;
request: unknown;
result?: string;
error?: string;
}): string {
let logEntry = `${toolName}\n`;
logEntry += formatToolInput(request);
if (error) {
logEntry += formatIndentedField("error", error);
} else if (result) {
logEntry += formatToolResult(result);
}
logEntry += "\n";
return logEntry;
}
/**
* Finds a CLI executable path by checking if it's installed globally
* @param name The name of the CLI executable to find