GitHub Copilot Programmatic Access
Problem Statement
GitHub Copilot provides AI-powered code completions directly within supported IDEs through official plugins. However, developers often need programmatic access to:
- Automatically capture Copilot's top suggestions
- Integrate completions into custom tools/pipelines
- Analyze or log Copilot's output systematically
The key challenge is that GitHub doesn't provide an official public API for programmatic Copilot access. This article demonstrates practical solutions to capture Copilot's suggestions programmatically using current (2023-2025) methods.
Core Requirements
To use these solutions, you must:
- Have an active GitHub Copilot subscription
- Install Node.js (v14+)
- Complete GitHub authentication
Official Language Server Method
The recommended approach uses GitHub's official @github/copilot-language-server
(since Dec 2023). It communicates via Language Server Protocol (LSP).
Step 1: Install the Language Server
npm install @github/copilot-language-server
Step 2: Basic Node.js Client Implementation
Create client.js
:
const { fork } = require('node:child_process');
const lspServer = fork(
'./node_modules/@github/copilot-language-server/dist/language-server.js',
['--stdio', 'true'],
{ silent: true }
);
let requestId = 0;
const pendingRequests = new Map();
lspServer.stdout.on('data', (data) => {
const payloads = data.toString()
.split(/Content-Length: \d+\r\n\r\n/)
.filter(Boolean);
for (const payload of payloads) {
try {
const message = JSON.parse(payload);
if (message.id && pendingRequests.has(message.id)) {
pendingRequests.get(message.id)(message);
pendingRequests.delete(message.id);
}
} catch (e) {}
}
});
async function sendRequest(method, params) {
const id = ++requestId;
const message = {
id,
method,
params,
jsonrpc: '2.0'
};
return new Promise(resolve => {
pendingRequests.set(id, resolve);
const content = JSON.stringify(message);
lspServer.stdin.write(`Content-Length: ${content.length}\r\n\r\n${content}`);
});
}
async function initialize() {
await sendRequest('initialize', {
capabilities: { workspace: { workspaceFolders: true } },
});
// Open document to complete
await sendRequest('textDocument/didOpen', {
textDocument: {
uri: 'file:///your-project/test.py',
languageId: 'python',
version: 1,
text: 'def find_max(arr):\n '
}
});
// Get completions at line 1, character 4
const completions = await sendRequest('getCompletions', {
doc: {
uri: 'file:///your-project/test.py',
position: { line: 1, character: 4 },
version: 1
}
});
console.log('Top Suggestions:');
completions.items.slice(0, 3).forEach((item, i) => {
console.log(`${i + 1}: ${item.text}`);
});
lspServer.kill();
}
initialize().catch(console.error);
Execution and Output
node client.js
Example output showing top 3 suggestions:
Top Suggestions:
1: max_val = arr[0]
2: max = arr[0]
3: maximum = arr[0]
Authentication
You must authenticate before first use:
- Run Copilot in any supported IDE and sign in
- The language server reuses stored credentials
- For headless environments, implement OAuth flow using
signInInitiate
/signInConfirm
LSP methods
Unofficial API Method
For a simpler interface, use the copilot-api wrapper.
Step 1: Install and Start Service
git clone https://github.com/B00TK1D/copilot-api.git
cd copilot-api
npm install
node server.js
Step 2: Get Completions via API
import requests
response = requests.post(
'http://localhost:8000/completions',
json={
'prompt': 'def find_max(arr):\n ',
'language': 'python'
}
)
if response.status_code == 200:
suggestions = response.json()['completions']
for i, suggestion in enumerate(suggestions[:3]):
print(f"Suggestion {i+1}: {suggestion}")
Output
Suggestion 1: max_val = arr[0]
Suggestion 2: max = arr[0]
Suggestion 3: max_value = arr[0]
Key Implementation Notes
Document Context Matters:
Provide full file context for contextual completions usingtextDocument/didChange
Handling Multiple Results:
UsegetCompletionsCycling
for expanded suggestions beyond top itemsAuthentication Maintenance:
Tokens expire every 24 hours - implement token refresh logicAlternatives:
markdown- **Logging Method:** Wrap existing Copilot agents to log stdin/stdout (see [B00TK1D's agent wrapper](https://github.com/B00TK1D/copilot-api#wrapping-copilot-agent)) - **OpenAI API:** While similar, GPT models won't match Copilot's code-specific optimizations
Official Limitations
These methods:
- Violate GitHub's ToS if used commercially
- May break with undocumented API changes
- Provide no service guarantees
Recommendation Path
Use the official language server for maximum flexibility and direct access to completion behavior matching IDE extensions. Choose the API wrapper for quick prototyping without LSP complexity. Both methods require accepting the limitations of unofficial solutions.
Final Note: Monitor the Copilot for CLI project and Copilot Voice extensions for future official programmatic pathways.