github-mcp 0.5.7

GitHub v3 REST API MCP server, generated by mcpify.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// GitHub v3 REST API MCP server — generated by mcpify. Do not hand-edit.
//
// Generic operationId -> HTTP request dispatcher (rather than one method
// per operation), so generation stays robust against specs with hundreds
// of operations and this file's size never grows with the spec.

use std::collections::HashMap;
use std::time::Duration;

use serde_json::{Map, Value};

use crate::auth::auth_manager::AuthManager;
use crate::auth::request_credentials::RequestCredentials;
use crate::core::api_url_builder::build_api_url;
use crate::core::circuit_breaker::{CircuitBreaker, CircuitBreakerError};
use crate::core::config_schema::Config;
use crate::core::rate_limiter::RateLimiter;
use crate::data::store::EndpointRecord;

fn parameters_of(endpoint: &EndpointRecord) -> Vec<Value> {
    endpoint
        .input_schema
        .get("parameters")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default()
}

fn names_with_location(endpoint: &EndpointRecord, location: &str) -> Vec<String> {
    parameters_of(endpoint)
        .iter()
        .filter(|param| param.get("in").and_then(Value::as_str) == Some(location))
        .filter_map(|param| param.get("name").and_then(Value::as_str).map(String::from))
        .collect()
}

fn value_to_plain_string(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// Substitutes every `{name}` path template segment with the matching
/// argument, percent-encoded — mirrors `targets::typescript`'s
/// regex-based `applyPathParams`, done here with a manual scan rather
/// than a `regex`-crate dependency this codebase otherwise has no use for.
fn apply_path_params(endpoint: &EndpointRecord, args: &Map<String, Value>) -> String {
    let mut result = String::new();
    let mut chars = endpoint.path.chars().peekable();
    while let Some(c) = chars.next() {
        if c != '{' {
            result.push(c);
            continue;
        }
        let mut name = String::new();
        for next in chars.by_ref() {
            if next == '}' {
                break;
            }
            name.push(next);
        }
        let value = args
            .get(&name)
            .map(value_to_plain_string)
            .unwrap_or_default();
        result.push_str(
            &percent_encoding::utf8_percent_encode(&value, percent_encoding::NON_ALPHANUMERIC)
                .to_string(),
        );
    }
    result
}

fn pick_by_location(
    endpoint: &EndpointRecord,
    args: &Map<String, Value>,
    location: &str,
) -> Vec<(String, String)> {
    names_with_location(endpoint, location)
        .into_iter()
        .filter_map(|name| {
            args.get(&name)
                .map(|value| (name.clone(), value_to_plain_string(value)))
        })
        .collect()
}

pub struct ApiClient {
    config: Config,
    client: reqwest::Client,
    circuit_breaker: CircuitBreaker,
    rate_limiter: RateLimiter,
}

impl ApiClient {
    pub fn new(config: Config) -> Self {
        let rate_limiter = RateLimiter::new(config.rate_limit as usize, Duration::from_secs(1));
        Self {
            client: reqwest::Client::new(),
            circuit_breaker: CircuitBreaker::default(),
            rate_limiter,
            config,
        }
    }

    /// Executes `endpoint` against the configured target API, retrying
    /// transient failures up to `config.retry_attempts` times, all inside
    /// the circuit breaker and rate limiter (REQ-2.3.3). `args` may
    /// contain a `body` key holding the JSON request body, alongside any
    /// path/query/header parameter values.
    pub async fn execute(
        &self,
        endpoint: &EndpointRecord,
        args: &Value,
        auth_manager: &mut AuthManager,
        request_override: Option<&RequestCredentials>,
    ) -> anyhow::Result<Value> {
        self.rate_limiter.acquire()?;

        let empty = Map::new();
        let args_map = args.as_object().unwrap_or(&empty);

        let query = pick_by_location(endpoint, args_map, "query");
        let path = apply_path_params(endpoint, args_map);
        let url = build_api_url(&self.config.url, &path, &query)?;

        let mut headers: HashMap<String, String> = HashMap::new();
        headers.insert("Content-Type".to_string(), "application/json".to_string());

        headers.insert(
            "Accept".to_string(),
            "application/vnd.github+json".to_string(),
        );

        headers.insert(
            "User-Agent".to_string(),
            "mcpify-client/0.1.0 (generated by mcpify)".to_string(),
        );

        for (name, value) in pick_by_location(endpoint, args_map, "header") {
            headers.insert(name, value);
        }
        let headers = auth_manager
            .apply_auth_headers(
                headers,
                &endpoint.method,
                &url,
                self.config.transport,
                request_override,
            )
            .await?;

        let body = args_map.get("body").cloned();

        match self
            .circuit_breaker
            .execute(|| self.dispatch(&endpoint.method, &url, body.as_ref(), &headers))
            .await
        {
            Ok(value) => Ok(value),
            Err(CircuitBreakerError::Open) => anyhow::bail!("circuit breaker is open"),
            Err(CircuitBreakerError::Inner(err)) => Err(err),
        }
    }

    async fn dispatch(
        &self,
        method: &str,
        url: &str,
        body: Option<&Value>,
        headers: &HashMap<String, String>,
    ) -> anyhow::Result<Value> {
        let parsed_method = reqwest::Method::from_bytes(method.as_bytes())?;

        let mut attempt = 0u32;
        loop {
            let mut request = self
                .client
                .request(parsed_method.clone(), url)
                .timeout(Duration::from_millis(self.config.timeout_ms));
            for (key, value) in headers {
                request = request.header(key, value);
            }
            if let Some(body) = body {
                request = request.json(body);
            } else if parsed_method != reqwest::Method::GET
                && parsed_method != reqwest::Method::HEAD
            {
                // Some APIs (e.g. Spotify's) 411 on a body-less PUT/POST/DELETE
                // with no Content-Length header — reqwest/hyper treats a
                // zero-length body the same as no body and still omits the
                // header on its own, so it has to be set explicitly.
                request = request
                    .header(reqwest::header::CONTENT_LENGTH, "0")
                    .body(Vec::new());
            }

            match request.send().await {
                Ok(response) => {
                    let value = response
                        .error_for_status()?
                        .json::<Value>()
                        .await
                        .unwrap_or(Value::Null);
                    return Ok(value);
                }
                Err(err) => {
                    attempt += 1;
                    if attempt > self.config.retry_attempts {
                        return Err(err.into());
                    }
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    use super::*;
    use crate::auth::auth_strategy::Credentials;
    use crate::core::config_schema::AuthMethod;
    async fn mock_http(
        status: &'static str,
        body: &'static str,
    ) -> (String, Arc<Mutex<String>>, tokio::task::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let captured = Arc::new(Mutex::new(String::new()));
        let request = captured.clone();
        let handle = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            let mut bytes = Vec::new();
            let mut buffer = [0u8; 4096];
            loop {
                let read = stream.read(&mut buffer).await.unwrap();
                if read == 0 {
                    break;
                }
                bytes.extend_from_slice(&buffer[..read]);
                let headers_end = bytes
                    .windows(4)
                    .position(|window| window == b"\r\n\r\n")
                    .map(|index| index + 4);
                if let Some(headers_end) = headers_end {
                    let headers = String::from_utf8_lossy(&bytes[..headers_end]);
                    let content_length = headers
                        .lines()
                        .find_map(|line| {
                            line.to_ascii_lowercase()
                                .strip_prefix("content-length:")
                                .and_then(|value| value.trim().parse::<usize>().ok())
                        })
                        .unwrap_or(0);
                    if bytes.len() >= headers_end + content_length {
                        break;
                    }
                }
            }
            *request.lock().unwrap() = String::from_utf8_lossy(&bytes).into_owned();
            let wire = format!(
                "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                body.len()
            );
            stream.write_all(wire.as_bytes()).await.unwrap();
        });
        (format!("http://{address}"), captured, handle)
    }

    async fn disconnecting_server() -> String {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        tokio::spawn(async move {
            for _ in 0..4 {
                let Ok((stream, _)) = listener.accept().await else {
                    break;
                };
                drop(stream);
            }
        });
        format!("http://{address}")
    }

    fn client(url: String, retry_attempts: u32) -> ApiClient {
        let config: Config = serde_json::from_value(serde_json::json!({
            "url": url,

            "auth_method": "pat",

            "retry_attempts": retry_attempts,
            "timeout_ms": 200
        }))
        .unwrap();
        ApiClient::new(config)
    }

    fn endpoint(path: &str, input_schema: Value) -> EndpointRecord {
        EndpointRecord {
            operation_id: "op".to_string(),
            path: path.to_string(),
            method: "GET".to_string(),
            summary: None,
            description: None,
            input_schema,
            output_schema: Value::Null,
            auth_scheme_ref: None,
        }
    }

    #[test]
    fn substitutes_path_parameters() {
        let endpoint = endpoint("/widgets/{id}", Value::Null);
        let args = Map::from_iter([("id".to_string(), Value::String("abc 123".to_string()))]);
        assert_eq!(apply_path_params(&endpoint, &args), "/widgets/abc%20123");
    }

    #[test]
    fn leaves_a_path_without_placeholders_untouched() {
        let endpoint = endpoint("/widgets", Value::Null);
        assert_eq!(apply_path_params(&endpoint, &Map::new()), "/widgets");
    }

    #[test]
    fn picks_query_parameters_by_declared_location() {
        let endpoint = endpoint(
            "/widgets",
            serde_json::json!({
                "parameters": [
                    { "in": "query", "name": "limit" },
                    { "in": "header", "name": "X-Trace-Id" },
                ]
            }),
        );
        let args = Map::from_iter([
            ("limit".to_string(), serde_json::json!(10)),
            ("X-Trace-Id".to_string(), Value::String("abc".to_string())),
        ]);

        let query = pick_by_location(&endpoint, &args, "query");
        assert_eq!(query, vec![("limit".to_string(), "10".to_string())]);

        let headers = pick_by_location(&endpoint, &args, "header");
        assert_eq!(headers, vec![("X-Trace-Id".to_string(), "abc".to_string())]);
    }

    #[tokio::test]
    async fn dispatch_sends_json_and_empty_bodies_and_parses_responses() {
        let (url, request, server) = mock_http("200 OK", r#"{"ok":true}"#).await;
        let response = client(url.clone(), 0)
            .dispatch(
                "POST",
                &url,
                Some(&serde_json::json!({ "name": "coverage" })),
                &HashMap::from([("X-Coverage".to_string(), "yes".to_string())]),
            )
            .await
            .unwrap();
        assert_eq!(response, serde_json::json!({ "ok": true }));
        server.await.unwrap();
        {
            let request = request.lock().unwrap();
            assert!(request.contains(r#"{"name":"coverage"}"#));
            assert!(request.to_ascii_lowercase().contains("x-coverage: yes"));
        }

        let (url, request, server) = mock_http("204 No Content", "").await;
        let response = client(url.clone(), 0)
            .dispatch("DELETE", &url, None, &HashMap::new())
            .await
            .unwrap();
        assert_eq!(response, Value::Null);
        server.await.unwrap();
        assert!(
            request
                .lock()
                .unwrap()
                .to_ascii_lowercase()
                .contains("content-length: 0")
        );
    }

    #[tokio::test]
    async fn dispatch_surfaces_method_status_and_retry_exhaustion_errors() {
        let local_url = disconnecting_server().await;
        let invalid_method = client(local_url.clone(), 0)
            .dispatch("NOT A METHOD", &local_url, None, &HashMap::new())
            .await;
        assert!(invalid_method.is_err());

        let (url, _, server) = mock_http("500 Internal Server Error", "{}").await;
        assert!(
            client(url.clone(), 0)
                .dispatch("GET", &url, None, &HashMap::new())
                .await
                .is_err()
        );
        server.await.unwrap();

        let local_url = disconnecting_server().await;
        assert!(
            client(local_url.clone(), 1)
                .dispatch("GET", &local_url, None, &HashMap::new())
                .await
                .is_err()
        );
    }

    fn seeded_auth_manager() -> AuthManager {
        let mut manager = AuthManager::new(AuthMethod::Pat);
        manager.set_credentials(Credentials::from([(
            "token".to_string(),
            "s3cr3t".to_string(),
        )]));
        manager
    }

    #[tokio::test]
    async fn execute_builds_the_url_applies_auth_and_parses_the_response() {
        let (url, request, server) = mock_http("200 OK", r#"{"ok":true}"#).await;
        let api_client = client(url.clone(), 0);
        let endpoint = EndpointRecord {
            operation_id: "op".to_string(),
            path: "/widgets/{id}".to_string(),
            method: "GET".to_string(),
            summary: None,
            description: None,
            input_schema: serde_json::json!({
                "parameters": [
                    { "in": "path", "name": "id" },
                    { "in": "query", "name": "limit" },
                ]
            }),
            output_schema: Value::Null,
            auth_scheme_ref: None,
        };
        let args = serde_json::json!({ "id": "abc 123", "limit": 5 });
        let mut auth_manager = seeded_auth_manager();

        let response = api_client
            .execute(&endpoint, &args, &mut auth_manager, None)
            .await
            .unwrap();
        assert_eq!(response, serde_json::json!({ "ok": true }));
        server.await.unwrap();

        let request = request.lock().unwrap();
        assert!(request.contains("GET /widgets/abc%20123?limit=5 HTTP/1.1"));
        assert!(
            request
                .to_ascii_lowercase()
                .contains("authorization: bearer s3cr3t")
        );
    }

    #[tokio::test]
    async fn execute_surfaces_a_dispatch_error_through_the_circuit_breaker() {
        let local_url = disconnecting_server().await;
        let api_client = client(local_url.clone(), 0);
        let endpoint = endpoint("/widgets", Value::Null);
        let mut auth_manager = seeded_auth_manager();

        let result = api_client
            .execute(&endpoint, &Value::Null, &mut auth_manager, None)
            .await;
        assert!(result.is_err());
    }
}