MCP HubMCP Hub
스킬 목록으로 돌아가기

use-graphql-api

pjt222
업데이트됨 Yesterday
3 조회
17
2
17
GitHub에서 보기
메타aiapiautomationdesigndata

정보

이 스킬은 개발자가 명령줄에서 직접 GraphQL API와 상호작용할 수 있게 해줍니다. 스키마 인트로스펙션, 쿼리/뮤테이션 구성, `gh api` 또는 `curl`을 통한 호출 실행, `jq`로 응답 파싱 등의 기능을 제공합니다. GitHub 워크플로우 자동화나 CLI 스크립트 및 자동화 프로세스에 GraphQL 엔드포인트를 통합하는 데 사용하세요.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/use-graphql-api

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Use GraphQL API

Discover, construct, execute, chain GraphQL operations from command line.

When Use

  • Query or mutate data via GraphQL endpoint (GitHub, Hasura, Apollo, etc.)
  • Automate GitHub operations needing GraphQL (Discussions, Projects v2)
  • Build shell scripts fetching structured data from GraphQL APIs
  • Chain multiple GraphQL calls where output of one feeds next

Inputs

  • Required: GraphQL endpoint URL or service name (e.g., github)
  • Required: Operation intent (what data to read or write)
  • Optional: Auth token or method (default: gh CLI auth for GitHub)
  • Optional: Output format preference (raw JSON, jq-filtered, variable assignment)

Steps

Step 1. Discover Schema

Determine available types, fields, queries, mutations.

For GitHub:

# List available query fields
gh api graphql -f query='{ __schema { queryType { fields { name description } } } }' \
  | jq '.data.__schema.queryType.fields[] | {name, description}'

# List available mutation fields
gh api graphql -f query='{ __schema { mutationType { fields { name description } } } }' \
  | jq '.data.__schema.mutationType.fields[] | {name, description}'

# Inspect a specific type
gh api graphql -f query='{
  __type(name: "Repository") {
    fields { name type { name kind ofType { name } } }
  }
}' | jq '.data.__type.fields[] | {name, type: .type.name // .type.ofType.name}'

For generic endpoints:

# Full introspection query via curl
curl -s -X POST https://api.example.com/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{"query":"{ __schema { types { name kind fields { name } } } }"}' \
  | jq '.data.__schema.types[] | select(.kind == "OBJECT") | {name, fields: [.fields[].name]}'

Got: JSON output listing available types, fields, mutations. Schema response confirms endpoint reachable, auth token valid.

If fail:

  • 401 Unauthorized — verify token. For GitHub, run gh auth status
  • Cannot query field — endpoint may disable introspection. Consult docs instead
  • Connection refused — verify endpoint URL, network access

Step 2. Identify Operation Type

Determine whether task needs query (read), mutation (write), or subscription (stream).

IntentOperationExample
Fetch dataqueryGet repository details, list discussions
Create/update/deletemutationCreate discussion, add comment
Real-time updatessubscriptionWatch for new issues (rare in CLI)

For GitHub-specific operations, consult GitHub GraphQL API docs.

# Quick check: does the mutation exist?
gh api graphql -f query='{ __schema { mutationType { fields { name } } } }' \
  | jq '.data.__schema.mutationType.fields[].name' | grep -i "discussion"

Got: Clear identification of whether query or mutation needed. Plus exact operation name (e.g., createDiscussion, repository).

If fail:

  • Operation not found — search with broader terms or check API version
  • Unclear whether query or mutation — action changes state? It's mutation

Step 3. Construct Operation

Build GraphQL query or mutation with fields, arguments, variables.

Query example — fetch repository's discussion categories:

gh api graphql -f query='
  query($owner: String!, $repo: String!) {
    repository(owner: $owner, name: $repo) {
      discussionCategories(first: 10) {
        nodes { id name }
      }
    }
  }
' -f owner="OWNER" -f repo="REPO" | jq '.data.repository.discussionCategories.nodes'

Mutation example — create GitHub Discussion:

gh api graphql -f query='
  mutation($repoId: ID!, $categoryId: ID!, $title: String!, $body: String!) {
    createDiscussion(input: {
      repositoryId: $repoId,
      categoryId: $categoryId,
      title: $title,
      body: $body
    }) {
      discussion { url number }
    }
  }
' -f repoId="$REPO_ID" -f categoryId="$CAT_ID" \
  -f title="My Discussion" -f body="Discussion body here"

Key construction rules:

  1. Always use variables ($var: Type!) instead of inline values for reusability
  2. Request only fields needed to minimize response size
  3. Use first: N with nodes for paginated connections
  4. Add id to every object selection — needed for chaining

Got: Syntactically valid GraphQL operation with appropriate variables, field selections, pagination parameters.

If fail:

  • Syntax errors — check bracket matching, trailing commas (GraphQL has no trailing commas)
  • Type mismatch — verify variable types against schema (e.g., ID! vs String!)
  • Missing required fields — add required input fields per schema

Step 4. Execute via CLI

Run operation. Capture response.

GitHub — using gh api graphql:

# Simple query
gh api graphql -f query='{ viewer { login } }'

# With variables
gh api graphql \
  -f query='query($owner: String!, $repo: String!) {
    repository(owner: $owner, name: $repo) { id name }
  }' \
  -f owner="octocat" -f repo="Hello-World"

# With jq post-processing
REPO_ID=$(gh api graphql \
  -f query='query($owner: String!, $repo: String!) {
    repository(owner: $owner, name: $repo) { id }
  }' \
  -f owner="OWNER" -f repo="REPO" \
  --jq '.data.repository.id')

Generic endpoint — using curl:

curl -s -X POST "$GRAPHQL_ENDPOINT" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d "$(jq -n \
    --arg query 'query { users { id name } }' \
    '{query: $query}'
  )"

Got: JSON response with data key containing requested fields, or errors array if operation failed.

If fail:

  • errors array in response — read message. Common causes: missing permissions, invalid IDs, rate limits
  • Empty data — query matched no records. Verify input values
  • HTTP 403 — token lacks required scope. For GitHub, check gh auth status. Add scopes with gh auth refresh -s scope

Step 5. Parse Response

Extract data needed from JSON response.

# Extract a single value
gh api graphql -f query='{ viewer { login } }' --jq '.data.viewer.login'

# Extract from a list
gh api graphql -f query='
  query($owner: String!, $repo: String!) {
    repository(owner: $owner, name: $repo) {
      issues(first: 5, states: OPEN) {
        nodes { number title }
      }
    }
  }
' -f owner="OWNER" -f repo="REPO" \
  --jq '.data.repository.issues.nodes[] | "\(.number): \(.title)"'

# Assign to a variable for later use
CATEGORY_ID=$(gh api graphql -f query='
  query($owner: String!, $repo: String!) {
    repository(owner: $owner, name: $repo) {
      discussionCategories(first: 20) {
        nodes { id name }
      }
    }
  }
' -f owner="OWNER" -f repo="REPO" \
  --jq '.data.repository.discussionCategories.nodes[] | select(.name == "Show and Tell") | .id')

Got: Clean, extracted values ready for display or assignment to shell variables.

If fail:

  • jq returns null — field path wrong. Pipe raw JSON to jq . first to inspect structure
  • Multiple values when expecting one — add select() filter or | first
  • Unicode issues — add -r to jq for raw string output

Step 6. Chain Operations

Use output from one operation as input to next.

# Step A: Get the repository ID
REPO_ID=$(gh api graphql \
  -f query='query($owner: String!, $repo: String!) {
    repository(owner: $owner, name: $repo) { id }
  }' \
  -f owner="$OWNER" -f repo="$REPO" \
  --jq '.data.repository.id')

# Step B: Get the discussion category ID
CAT_ID=$(gh api graphql \
  -f query='query($owner: String!, $repo: String!) {
    repository(owner: $owner, name: $repo) {
      discussionCategories(first: 20) {
        nodes { id name }
      }
    }
  }' \
  -f owner="$OWNER" -f repo="$REPO" \
  --jq '.data.repository.discussionCategories.nodes[]
    | select(.name == "Show and Tell") | .id')

# Step C: Create the discussion using both IDs
RESULT=$(gh api graphql \
  -f query='mutation($repoId: ID!, $catId: ID!, $title: String!, $body: String!) {
    createDiscussion(input: {
      repositoryId: $repoId,
      categoryId: $catId,
      title: $title,
      body: $body
    }) {
      discussion { url number }
    }
  }' \
  -f repoId="$REPO_ID" -f catId="$CAT_ID" \
  -f title="$TITLE" -f body="$BODY" \
  --jq '.data.createDiscussion.discussion')

echo "Created: $(echo "$RESULT" | jq -r '.url')"

Pattern: Always extract id fields in earlier queries so they pass as ID! variables to subsequent mutations.

Got: Multi-step workflow where each call succeeds. IDs flow correct between operations.

If fail:

  • Variable empty — previous step failed silent. Add set -e. Check each intermediate value
  • ID format wrong — GitHub node IDs are opaque strings (e.g., R_kgDO...). Never construct manually
  • Rate limited — add sleep 1 between calls or batch queries using aliases

Checks

  1. Introspection query returns schema data (Step 1 succeeds)
  2. Constructed queries syntactically valid (no GraphQL parser errors)
  3. Responses contain data keys without errors
  4. Extracted values match expected types (IDs non-empty strings, counts numbers)
  5. Chained operations complete end-to-end (mutation uses IDs from prior queries)

Pitfalls

PitfallPrevention
Forget ! on required variable typesAlways check schema for nullability. Most input fields non-null (!)
Use REST IDs in GraphQLGraphQL uses opaque node IDs. Fetch via GraphQL, not REST
No paginate large result setsUse first/after with pageInfo { hasNextPage endCursor }
Hardcode IDs instead of queryingIDs differ between environments. Always query dynamic
Ignore errors arrayCheck for errors even when data present — partial errors possible
Shell quoting issues with nested JSONUse --jq flag with gh or pipe through jq separate

See Also

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman/skills/use-graphql-api
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기