connectors 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +35 -0
  3. data/CONNECTORS_FRAMEWORK.md +799 -0
  4. data/CONTRIBUTING.md +60 -0
  5. data/MCP_CLIENT.md +168 -0
  6. data/MIT-LICENSE +20 -0
  7. data/README.md +146 -0
  8. data/app/connectors/clickup/connector.rb +13 -0
  9. data/app/connectors/gmail/api.rb +114 -0
  10. data/app/connectors/gmail/connector.rb +921 -0
  11. data/app/connectors/gmail/mime_builder.rb +261 -0
  12. data/app/connectors/gmail/mime_parser.rb +106 -0
  13. data/app/connectors/gmail/polling.rb +154 -0
  14. data/app/connectors/remote_mcp/connector.rb +18 -0
  15. data/app/connectors/resend/connector.rb +218 -0
  16. data/app/controllers/concerns/connectors/grant_access.rb +43 -0
  17. data/app/controllers/connectors/actions_controller.rb +66 -0
  18. data/app/controllers/connectors/application_controller.rb +5 -0
  19. data/app/controllers/connectors/credentials_controller.rb +245 -0
  20. data/app/controllers/connectors/grants_controller.rb +123 -0
  21. data/app/controllers/connectors/mcp_controller.rb +88 -0
  22. data/app/controllers/connectors/oauth_controller.rb +134 -0
  23. data/app/controllers/connectors/types_controller.rb +144 -0
  24. data/app/controllers/connectors/webhooks_controller.rb +105 -0
  25. data/app/jobs/connectors/application_job.rb +4 -0
  26. data/app/jobs/connectors/deliver_webhook_job.rb +27 -0
  27. data/app/jobs/connectors/poll_job.rb +49 -0
  28. data/app/models/connectors/application_record.rb +5 -0
  29. data/app/models/connectors/credential_share.rb +31 -0
  30. data/app/models/connectors/grant.rb +103 -0
  31. data/app/models/connectors/mcp_authorization.rb +6 -0
  32. data/app/models/connectors/mcp_interaction.rb +6 -0
  33. data/app/models/connectors/poll_state.rb +17 -0
  34. data/app/models/connectors/webhook_event.rb +19 -0
  35. data/config/routes.rb +68 -0
  36. data/db/migrate/20260518210324_create_connectors_grants.rb +49 -0
  37. data/db/migrate/20260518214609_create_connectors_webhook_events.rb +35 -0
  38. data/db/migrate/20260521140000_create_connectors_credential_shares.rb +26 -0
  39. data/db/migrate/20260922120000_create_connectors_poll_states.rb +12 -0
  40. data/db/migrate/20260922130000_create_connectors_mcp_transactions.rb +18 -0
  41. data/docs/adding-connectors.md +92 -0
  42. data/docs/architecture.md +71 -0
  43. data/docs/releasing.md +60 -0
  44. data/lib/connectors/action.rb +90 -0
  45. data/lib/connectors/action_builder.rb +125 -0
  46. data/lib/connectors/action_runner.rb +99 -0
  47. data/lib/connectors/auth/scheme/api_key.rb +51 -0
  48. data/lib/connectors/auth/scheme/oauth2.rb +23 -0
  49. data/lib/connectors/auth/scheme.rb +35 -0
  50. data/lib/connectors/auth.rb +4 -0
  51. data/lib/connectors/auth_injection.rb +65 -0
  52. data/lib/connectors/client_builder.rb +87 -0
  53. data/lib/connectors/configuration.rb +138 -0
  54. data/lib/connectors/connector.rb +565 -0
  55. data/lib/connectors/credential_schema.rb +219 -0
  56. data/lib/connectors/credential_tester.rb +85 -0
  57. data/lib/connectors/credential_type_registry.rb +162 -0
  58. data/lib/connectors/credential_types/http_auth.rb +171 -0
  59. data/lib/connectors/engine.rb +123 -0
  60. data/lib/connectors/errors.rb +88 -0
  61. data/lib/connectors/grant_policy.rb +13 -0
  62. data/lib/connectors/mcp/access.rb +50 -0
  63. data/lib/connectors/mcp/authorization.rb +177 -0
  64. data/lib/connectors/mcp/authorization_context.rb +25 -0
  65. data/lib/connectors/mcp/authorization_discovery.rb +42 -0
  66. data/lib/connectors/mcp/cancellation.rb +36 -0
  67. data/lib/connectors/mcp/client.rb +137 -0
  68. data/lib/connectors/mcp/connection_config.rb +48 -0
  69. data/lib/connectors/mcp/http.rb +108 -0
  70. data/lib/connectors/mcp/interaction.rb +82 -0
  71. data/lib/connectors/mcp/pending_transaction.rb +26 -0
  72. data/lib/connectors/mcp/protocol/2026-07-28.json +3963 -0
  73. data/lib/connectors/mcp/protocol/LICENSE +216 -0
  74. data/lib/connectors/mcp/protocol/README.md +8 -0
  75. data/lib/connectors/mcp/protocol_schema.rb +30 -0
  76. data/lib/connectors/mcp/schema.rb +45 -0
  77. data/lib/connectors/mcp/settings.rb +27 -0
  78. data/lib/connectors/mcp/token_endpoint.rb +48 -0
  79. data/lib/connectors/mcp/transport.rb +105 -0
  80. data/lib/connectors/mcp.rb +69 -0
  81. data/lib/connectors/middleware/authenticate_generic.rb +79 -0
  82. data/lib/connectors/middleware/auto_refresh.rb +71 -0
  83. data/lib/connectors/middleware/error_normalization.rb +45 -0
  84. data/lib/connectors/middleware/grant_status.rb +19 -0
  85. data/lib/connectors/middleware/pre_authentication.rb +54 -0
  86. data/lib/connectors/middleware/rate_limit.rb +40 -0
  87. data/lib/connectors/oauth/authorize_url.rb +78 -0
  88. data/lib/connectors/oauth/client_authentication.rb +24 -0
  89. data/lib/connectors/oauth/client_credentials.rb +43 -0
  90. data/lib/connectors/oauth/grant_writer.rb +73 -0
  91. data/lib/connectors/oauth/pkce.rb +32 -0
  92. data/lib/connectors/oauth/revoke.rb +72 -0
  93. data/lib/connectors/oauth/state.rb +41 -0
  94. data/lib/connectors/oauth/token_exchange.rb +69 -0
  95. data/lib/connectors/oauth/token_response.rb +40 -0
  96. data/lib/connectors/oauth.rb +4 -0
  97. data/lib/connectors/oauth1.rb +151 -0
  98. data/lib/connectors/permission_check.rb +33 -0
  99. data/lib/connectors/poll_runner.rb +50 -0
  100. data/lib/connectors/pre_authentication_helpers.rb +76 -0
  101. data/lib/connectors/registry.rb +38 -0
  102. data/lib/connectors/version.rb +3 -0
  103. data/lib/connectors/webhook_context.rb +62 -0
  104. data/lib/connectors/webhook_lifecycle.rb +69 -0
  105. data/lib/connectors/webhook_methods.rb +48 -0
  106. data/lib/connectors/webhooks/verifier.rb +31 -0
  107. data/lib/connectors/webhooks.rb +5 -0
  108. data/lib/connectors.rb +50 -0
  109. data/lib/tasks/connectors_mcp.rake +9 -0
  110. data/lib/tasks/connectors_tasks.rake +4 -0
  111. data/openapi.yaml +1099 -0
  112. metadata +263 -0
@@ -0,0 +1,216 @@
1
+ The MCP project is undergoing a licensing transition from the MIT License to the Apache License, Version 2.0 ("Apache-2.0"). All new code and specification contributions to the project are licensed under Apache-2.0. Documentation contributions (excluding specifications) are licensed under CC-BY-4.0.
2
+
3
+ Contributions for which relicensing consent has been obtained are licensed under Apache-2.0. Contributions made by authors who originally licensed their work under the MIT License and who have not yet granted explicit permission to relicense remain licensed under the MIT License.
4
+
5
+ No rights beyond those granted by the applicable original license are conveyed for such contributions.
6
+
7
+ ---
8
+
9
+ Apache License
10
+ Version 2.0, January 2004
11
+ http://www.apache.org/licenses/
12
+
13
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
14
+
15
+ 1. Definitions.
16
+
17
+ "License" shall mean the terms and conditions for use, reproduction,
18
+ and distribution as defined by Sections 1 through 9 of this document.
19
+
20
+ "Licensor" shall mean the copyright owner or entity authorized by
21
+ the copyright owner that is granting the License.
22
+
23
+ "Legal Entity" shall mean the union of the acting entity and all
24
+ other entities that control, are controlled by, or are under common
25
+ control with that entity. For the purposes of this definition,
26
+ "control" means (i) the power, direct or indirect, to cause the
27
+ direction or management of such entity, whether by contract or
28
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
29
+ outstanding shares, or (iii) beneficial ownership of such entity.
30
+
31
+ "You" (or "Your") shall mean an individual or Legal Entity
32
+ exercising permissions granted by this License.
33
+
34
+ "Source" form shall mean the preferred form for making modifications,
35
+ including but not limited to software source code, documentation
36
+ source, and configuration files.
37
+
38
+ "Object" form shall mean any form resulting from mechanical
39
+ transformation or translation of a Source form, including but
40
+ not limited to compiled object code, generated documentation,
41
+ and conversions to other media types.
42
+
43
+ "Work" shall mean the work of authorship, whether in Source or
44
+ Object form, made available under the License, as indicated by a
45
+ copyright notice that is included in or attached to the work
46
+ (an example is provided in the Appendix below).
47
+
48
+ "Derivative Works" shall mean any work, whether in Source or Object
49
+ form, that is based on (or derived from) the Work and for which the
50
+ editorial revisions, annotations, elaborations, or other modifications
51
+ represent, as a whole, an original work of authorship. For the purposes
52
+ of this License, Derivative Works shall not include works that remain
53
+ separable from, or merely link (or bind by name) to the interfaces of,
54
+ the Work and Derivative Works thereof.
55
+
56
+ "Contribution" shall mean any work of authorship, including
57
+ the original version of the Work and any modifications or additions
58
+ to that Work or Derivative Works thereof, that is intentionally
59
+ submitted to the Licensor for inclusion in the Work by the copyright
60
+ owner or by an individual or Legal Entity authorized to submit on behalf
61
+ of the copyright owner. For the purposes of this definition, "submitted"
62
+ means any form of electronic, verbal, or written communication sent
63
+ to the Licensor or its representatives, including but not limited to
64
+ communication on electronic mailing lists, source code control systems,
65
+ and issue tracking systems that are managed by, or on behalf of, the
66
+ Licensor for the purpose of discussing and improving the Work, but
67
+ excluding communication that is conspicuously marked or otherwise
68
+ designated in writing by the copyright owner as "Not a Contribution."
69
+
70
+ "Contributor" shall mean Licensor and any individual or Legal Entity
71
+ on behalf of whom a Contribution has been received by Licensor and
72
+ subsequently incorporated within the Work.
73
+
74
+ 2. Grant of Copyright License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ copyright license to reproduce, prepare Derivative Works of,
78
+ publicly display, publicly perform, sublicense, and distribute the
79
+ Work and such Derivative Works in Source or Object form.
80
+
81
+ 3. Grant of Patent License. Subject to the terms and conditions of
82
+ this License, each Contributor hereby grants to You a perpetual,
83
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
84
+ (except as stated in this section) patent license to make, have made,
85
+ use, offer to sell, sell, import, and otherwise transfer the Work,
86
+ where such license applies only to those patent claims licensable
87
+ by such Contributor that are necessarily infringed by their
88
+ Contribution(s) alone or by combination of their Contribution(s)
89
+ with the Work to which such Contribution(s) was submitted. If You
90
+ institute patent litigation against any entity (including a
91
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
92
+ or a Contribution incorporated within the Work constitutes direct
93
+ or contributory patent infringement, then any patent licenses
94
+ granted to You under this License for that Work shall terminate
95
+ as of the date such litigation is filed.
96
+
97
+ 4. Redistribution. You may reproduce and distribute copies of the
98
+ Work or Derivative Works thereof in any medium, with or without
99
+ modifications, and in Source or Object form, provided that You
100
+ meet the following conditions:
101
+
102
+ (a) You must give any other recipients of the Work or
103
+ Derivative Works a copy of this License; and
104
+
105
+ (b) You must cause any modified files to carry prominent notices
106
+ stating that You changed the files; and
107
+
108
+ (c) You must retain, in the Source form of any Derivative Works
109
+ that You distribute, all copyright, patent, trademark, and
110
+ attribution notices from the Source form of the Work,
111
+ excluding those notices that do not pertain to any part of
112
+ the Derivative Works; and
113
+
114
+ (d) If the Work includes a "NOTICE" text file as part of its
115
+ distribution, then any Derivative Works that You distribute must
116
+ include a readable copy of the attribution notices contained
117
+ within such NOTICE file, excluding those notices that do not
118
+ pertain to any part of the Derivative Works, in at least one
119
+ of the following places: within a NOTICE text file distributed
120
+ as part of the Derivative Works; within the Source form or
121
+ documentation, if provided along with the Derivative Works; or,
122
+ within a display generated by the Derivative Works, if and
123
+ wherever such third-party notices normally appear. The contents
124
+ of the NOTICE file are for informational purposes only and
125
+ do not modify the License. You may add Your own attribution
126
+ notices within Derivative Works that You distribute, alongside
127
+ or as an addendum to the NOTICE text from the Work, provided
128
+ that such additional attribution notices cannot be construed
129
+ as modifying the License.
130
+
131
+ You may add Your own copyright statement to Your modifications and
132
+ may provide additional or different license terms and conditions
133
+ for use, reproduction, or distribution of Your modifications, or
134
+ for any such Derivative Works as a whole, provided Your use,
135
+ reproduction, and distribution of the Work otherwise complies with
136
+ the conditions stated in this License.
137
+
138
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
139
+ any Contribution intentionally submitted for inclusion in the Work
140
+ by You to the Licensor shall be under the terms and conditions of
141
+ this License, without any additional terms or conditions.
142
+ Notwithstanding the above, nothing herein shall supersede or modify
143
+ the terms of any separate license agreement you may have executed
144
+ with Licensor regarding such Contributions.
145
+
146
+ 6. Trademarks. This License does not grant permission to use the trade
147
+ names, trademarks, service marks, or product names of the Licensor,
148
+ except as required for reasonable and customary use in describing the
149
+ origin of the Work and reproducing the content of the NOTICE file.
150
+
151
+ 7. Disclaimer of Warranty. Unless required by applicable law or
152
+ agreed to in writing, Licensor provides the Work (and each
153
+ Contributor provides its Contributions) on an "AS IS" BASIS,
154
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
155
+ implied, including, without limitation, any warranties or conditions
156
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
157
+ PARTICULAR PURPOSE. You are solely responsible for determining the
158
+ appropriateness of using or redistributing the Work and assume any
159
+ risks associated with Your exercise of permissions under this License.
160
+
161
+ 8. Limitation of Liability. In no event and under no legal theory,
162
+ whether in tort (including negligence), contract, or otherwise,
163
+ unless required by applicable law (such as deliberate and grossly
164
+ negligent acts) or agreed to in writing, shall any Contributor be
165
+ liable to You for damages, including any direct, indirect, special,
166
+ incidental, or consequential damages of any character arising as a
167
+ result of this License or out of the use or inability to use the
168
+ Work (including but not limited to damages for loss of goodwill,
169
+ work stoppage, computer failure or malfunction, or any and all
170
+ other commercial damages or losses), even if such Contributor
171
+ has been advised of the possibility of such damages.
172
+
173
+ 9. Accepting Warranty or Additional Liability. While redistributing
174
+ the Work or Derivative Works thereof, You may choose to offer,
175
+ and charge a fee for, acceptance of support, warranty, indemnity,
176
+ or other liability obligations and/or rights consistent with this
177
+ License. However, in accepting such obligations, You may act only
178
+ on Your own behalf and on Your sole responsibility, not on behalf
179
+ of any other Contributor, and only if You agree to indemnify,
180
+ defend, and hold each Contributor harmless for any liability
181
+ incurred by, or claims asserted against, such Contributor by reason
182
+ of your accepting any such warranty or additional liability.
183
+
184
+ END OF TERMS AND CONDITIONS
185
+
186
+ ---
187
+
188
+ MIT License
189
+
190
+ Copyright (c) 2024-2025 Model Context Protocol a Series of LF Projects, LLC.
191
+
192
+ Permission is hereby granted, free of charge, to any person obtaining a copy
193
+ of this software and associated documentation files (the "Software"), to deal
194
+ in the Software without restriction, including without limitation the rights
195
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
196
+ copies of the Software, and to permit persons to whom the Software is
197
+ furnished to do so, subject to the following conditions:
198
+
199
+ The above copyright notice and this permission notice shall be included in all
200
+ copies or substantial portions of the Software.
201
+
202
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
203
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
204
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
205
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
206
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
207
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
208
+ SOFTWARE.
209
+
210
+ ---
211
+
212
+ Creative Commons Attribution 4.0 International (CC-BY-4.0)
213
+
214
+ Documentation in this project (excluding specifications) is licensed under
215
+ CC-BY-4.0. See https://creativecommons.org/licenses/by/4.0/legalcode for
216
+ the full license text.
@@ -0,0 +1,8 @@
1
+ # MCP protocol schema
2
+
3
+ Unmodified generated JSON Schema for MCP 2026-07-28 from:
4
+ https://github.com/modelcontextprotocol/modelcontextprotocol/blob/3f6e5e17e2a83b47dfb37b20d159e0e27efa316c/schema/2026-07-28/schema.json
5
+
6
+ The upstream license is included in LICENSE. This file is vendored to make response validation deterministic and avoid runtime network schema resolution. Update it only alongside protocol contract tests and a protocol-version change. Client compatibility normalization (absent resultType) lives in ProtocolSchema, not in this source artifact.
7
+
8
+ Application correction (2026-09-22): `ProtocolSchema` corrects only the in-memory `ElicitResult.content` numeric union from `integer` to `number`. The normative TypeScript definition at the same commit, [schema.ts line 3148](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/3f6e5e17e2a83b47dfb37b20d159e0e27efa316c/schema/2026-07-28/schema.ts#L3148), permits `string | number | boolean | string[]`. The generated JSON incorrectly narrows that member. The vendored JSON remains unmodified; `interaction_spec.rb` covers accepting a decimal form response.
@@ -0,0 +1,30 @@
1
+ module Connectors
2
+ module MCP
3
+ # The normative schema is an offline, pinned upstream artifact; do not recreate its types here.
4
+ module ProtocolSchema
5
+ DOCUMENT = JSON.parse(File.read(File.join(__dir__, "protocol/2026-07-28.json"))).freeze
6
+ VALIDATORS = %w[Tool CallToolResult InputRequiredResult ElicitRequest ElicitResult].to_h do |name|
7
+ document = DOCUMENT
8
+ if name == "ElicitResult"
9
+ # Normative schema.ts at the pinned commit, line 3148, permits `number`.
10
+ # The generated JSON incorrectly narrows this union member to integer.
11
+ document = DOCUMENT.deep_dup
12
+ alternatives = document.fetch("$defs").fetch(name).fetch("properties").fetch("content").fetch("additionalProperties").fetch("anyOf")
13
+ alternatives.last["type"] = %w[string number boolean]
14
+ end
15
+ [ name, JSONSchemer.schema(document.merge("$ref" => "#/$defs/#{name}"), ref_resolver: ->(_) { raise ProtocolError, "External protocol reference" }) ]
16
+ end.freeze
17
+ module_function
18
+
19
+ def validate!(name, value)
20
+ candidate = value
21
+ if %w[CallToolResult InputRequiredResult].include?(name) && value.is_a?(Hash) && !value.key?("resultType")
22
+ candidate = value.merge("resultType" => "complete")
23
+ end
24
+ Timeout.timeout(Connectors.configuration.mcp.schema_timeout, ProtocolError, "Protocol validation deadline exceeded") do
25
+ raise ProtocolError, "Invalid MCP #{name}" unless VALIDATORS.fetch(name).valid?(candidate)
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,45 @@
1
+ module Connectors
2
+ module MCP
3
+ class Schema
4
+ DIALECTS = %w[https://json-schema.org/draft/2020-12/schema http://json-schema.org/draft-07/schema#].freeze
5
+ def initialize(schema)
6
+ raise ValidationError, "Tool schema must be an object" unless schema.is_a?(Hash)
7
+ dialect = schema.fetch("$schema", DIALECTS.first)
8
+ raise ValidationError, "Unsupported schema dialect" unless DIALECTS.include?(dialect)
9
+ check_complexity!(schema)
10
+ resolver = ->(_uri) { raise ValidationError, "External schema references are disabled" }
11
+ @schema = JSONSchemer.schema(schema, ref_resolver: resolver)
12
+ bounded { raise ValidationError, "Invalid tool schema" unless @schema.valid_schema? }
13
+ rescue JSONSchemer::UnknownRef
14
+ raise ValidationError, "Unresolved schema reference"
15
+ end
16
+
17
+ def validate!(value)
18
+ bounded { raise ValidationError, "Value does not satisfy tool schema" unless @schema.valid?(value) }
19
+ rescue JSONSchemer::UnknownRef
20
+ raise ValidationError, "Unresolved schema reference"
21
+ end
22
+
23
+ private
24
+
25
+ def bounded(&block)
26
+ Timeout.timeout(Connectors.configuration.mcp.schema_timeout, ValidationError, "Schema validation deadline exceeded", &block)
27
+ end
28
+
29
+ def check_complexity!(schema)
30
+ nodes = [ [ schema, 0 ] ]
31
+ count = 0
32
+ until nodes.empty?
33
+ node, depth = nodes.pop
34
+ count += 1
35
+ raise ValidationError, "Schema is too complex" if count > Connectors.configuration.mcp.max_schema_nodes || depth > 50
36
+ children = node.is_a?(Hash) ? node.values : (node.is_a?(Array) ? node : [])
37
+ if node.is_a?(Hash) && node["$ref"].is_a?(String) && !node["$ref"].start_with?("#")
38
+ raise ValidationError, "External schema references are disabled"
39
+ end
40
+ children.each { |child| nodes << [ child, depth + 1 ] }
41
+ end
42
+ end
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,27 @@
1
+ module Connectors
2
+ module MCP
3
+ class Settings
4
+ attr_accessor :private_hosts, :allow_loopback_http, :client_name, :callback_url,
5
+ :client_metadata_url, :open_timeout, :request_timeout, :stream_timeout,
6
+ :max_bytes, :max_pages, :max_tools, :max_rounds, :transaction_ttl,
7
+ :schema_timeout, :max_schema_nodes, :elicitation_modes, :assertion_provider
8
+
9
+ def initialize
10
+ @private_hosts = []
11
+ @allow_loopback_http = false
12
+ @client_name = "Connectors"
13
+ @open_timeout = 5
14
+ @request_timeout = 30
15
+ @stream_timeout = 300
16
+ @max_bytes = 4 * 1024 * 1024
17
+ @max_pages = 100
18
+ @max_tools = 1000
19
+ @max_rounds = 10
20
+ @transaction_ttl = 15.minutes
21
+ @schema_timeout = 1
22
+ @max_schema_nodes = 10_000
23
+ @elicitation_modes = []
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,48 @@
1
+ require "base64"
2
+
3
+ module Connectors
4
+ module MCP
5
+ class TokenEndpoint
6
+ def self.exchange(metadata:, client:, params:)
7
+ method = client.fetch("token_endpoint_auth_method", "none")
8
+ supported = metadata.fetch("token_endpoint_auth_methods_supported", [ "client_secret_basic" ])
9
+ # Public clients are permitted when the AS omits auth-method metadata.
10
+ unless supported.include?(method) || (method == "none" && !metadata.key?("token_endpoint_auth_methods_supported"))
11
+ raise ConfigurationRequired, "Client authentication method is not advertised"
12
+ end
13
+ headers = { "Accept" => "application/json", "Content-Type" => "application/x-www-form-urlencoded" }
14
+ form = params.merge("client_id" => client.fetch("client_id"))
15
+ case method
16
+ when "none"
17
+ raise ConfigurationRequired, "Confidential client cannot use public authentication" if client["client_secret"].present?
18
+ when "client_secret_basic"
19
+ pair = %w[client_id client_secret].map { |key| URI.encode_www_form_component(client.fetch(key)) }.join(":")
20
+ headers["Authorization"] = "Basic #{Base64.strict_encode64(pair)}"
21
+ form.delete("client_id")
22
+ when "client_secret_post"
23
+ form["client_secret"] = client.fetch("client_secret")
24
+ when "private_key_jwt"
25
+ signer = Connectors.configuration.mcp.assertion_provider or raise ConfigurationRequired, "Client assertion provider is required"
26
+ form["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
27
+ form["client_assertion"] = signer.call(client.fetch("client_id"), metadata.fetch("token_endpoint"))
28
+ else
29
+ raise ConfigurationRequired, "Unsupported client authentication method"
30
+ end
31
+ tokens = HTTP.new.json(url: metadata.fetch("token_endpoint"), method: :post, headers: headers, body: URI.encode_www_form(form))
32
+ unless tokens["access_token"].is_a?(String) && tokens["access_token"].match?(/\A[A-Za-z0-9\-._~+\/]+=*\z/) && tokens["token_type"].to_s.casecmp?("Bearer")
33
+ raise ProtocolError, "Invalid OAuth token response"
34
+ end
35
+ if tokens.key?("expires_in")
36
+ raise ProtocolError, "Invalid token expiry" unless tokens["expires_in"].is_a?(Numeric) && tokens["expires_in"].finite? && tokens["expires_in"] >= 0
37
+ tokens["expires_at"] = Time.current.to_f + tokens["expires_in"]
38
+ end
39
+ if tokens.key?("refresh_token") && !tokens["refresh_token"].is_a?(String)
40
+ raise ProtocolError, "Invalid refresh token"
41
+ end
42
+ tokens
43
+ rescue KeyError
44
+ raise ConfigurationRequired, "Incomplete OAuth client information"
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,105 @@
1
+ module Connectors
2
+ module MCP
3
+ class Transport
4
+ def initialize(url:, headers: {}, capabilities: {})
5
+ @url, @headers, @capabilities = url, headers, capabilities
6
+ end
7
+
8
+ def request(method, params = {}, parameter_headers: {}, subscription: false, cancellation: nil)
9
+ id = SecureRandom.uuid
10
+ request = ::MCP::Client::ModernEnvelope.stamp(
11
+ { jsonrpc: "2.0", id: id, method: method, params: params },
12
+ protocol_version: PROTOCOL_VERSION,
13
+ client_info: { name: Connectors.configuration.mcp.client_name, version: Connectors::VERSION },
14
+ capabilities: @capabilities)
15
+ headers = @headers.merge("Content-Type" => "application/json", "Accept" => "application/json, text/event-stream",
16
+ "MCP-Protocol-Version" => PROTOCOL_VERSION, "Mcp-Method" => method).merge(parameter_headers)
17
+ headers["Mcp-Name"] = ::MCP::Client::McpParamHeaders.encode_value(params.fetch("name")) if method == "tools/call"
18
+ json = +""
19
+ parser = EventStreamParser::Parser.new
20
+ acknowledged = false
21
+ filter = {}
22
+ HTTP.new.call(url: @url, method: :post, headers: headers, body: JSON.generate(request), stream: subscription, cancellation: cancellation) do |chunk, response_headers|
23
+ case response_headers["content-type"].to_s.split(";").first
24
+ when "application/json"
25
+ raise ProtocolError, "Subscriptions require an event stream" if subscription
26
+ json << chunk
27
+ when "text/event-stream"
28
+ parser.feed(chunk) do |_type, data, _event_id|
29
+ next if data.empty?
30
+ message = parse(data)
31
+ if message.key?("id")
32
+ validate_response!(message, id)
33
+ raise ProtocolError, "Subscription completed before acknowledgment" if subscription && !acknowledged
34
+ if subscription && message.dig("result", "_meta", "io.modelcontextprotocol/subscriptionId") != id
35
+ raise ProtocolError, "Invalid subscription completion correlation"
36
+ end
37
+ return message.fetch("result")
38
+ end
39
+ validate_notification!(message)
40
+ if subscription
41
+ subscription_id = message.dig("params", "_meta", "io.modelcontextprotocol/subscriptionId")
42
+ raise ProtocolError, "Invalid subscription correlation" unless subscription_id == id
43
+ unless acknowledged
44
+ raise ProtocolError, "Missing subscription acknowledgment" unless message["method"] == "notifications/subscriptions/acknowledged"
45
+ filter = message.dig("params", "notifications")
46
+ requested = params.fetch("notifications", {})
47
+ unless filter.is_a?(Hash) && filter.all? { |key, value| value == true && requested[key] == true }
48
+ raise ProtocolError, "Invalid acknowledged subscription filter"
49
+ end
50
+ acknowledged = true
51
+ else
52
+ key = { "notifications/tools/list_changed" => "toolsListChanged", "notifications/prompts/list_changed" => "promptsListChanged", "notifications/resources/list_changed" => "resourcesListChanged" }[message["method"]]
53
+ raise ProtocolError, "Notification violates subscription filter" unless key && filter[key]
54
+ end
55
+ yield message if block_given?
56
+ end
57
+ end
58
+ else
59
+ raise ProtocolError, "Unsupported MCP response content type"
60
+ end
61
+ end
62
+ raise TransportError, "MCP stream ended without a result; outcome may be unknown" if json.empty?
63
+ message = parse(json)
64
+ validate_response!(message, id)
65
+ message.fetch("result")
66
+ rescue HTTPError => error
67
+ if error.status == 401 || (error.status == 403 && challenge(error)["error"] == "insufficient_scope")
68
+ raise AuthorizationRequired.new(challenge(error))
69
+ end
70
+ raise
71
+ end
72
+
73
+ private
74
+
75
+ def challenge(error)
76
+ ::MCP::Client::OAuth::Discovery.parse_www_authenticate(error.headers["www-authenticate"])
77
+ end
78
+
79
+ def parse(data)
80
+ value = JSON.parse(data)
81
+ raise ProtocolError, "Invalid JSON-RPC envelope" unless value.is_a?(Hash) && value["jsonrpc"] == "2.0"
82
+ value
83
+ rescue JSON::ParserError
84
+ raise ProtocolError, "Malformed MCP JSON"
85
+ end
86
+
87
+ def validate_notification!(message)
88
+ raise ProtocolError, "Invalid server notification" unless message["method"].is_a?(String) && !message.key?("result") && !message.key?("error")
89
+ end
90
+
91
+ def validate_response!(message, id)
92
+ raise ProtocolError, "Mismatched JSON-RPC response ID" unless message["id"] == id
93
+ if message.key?("error") && !message.key?("result")
94
+ error = message["error"]
95
+ raise ProtocolError, "Malformed JSON-RPC error" unless error.is_a?(Hash) && error["code"].is_a?(Integer) && error["message"].is_a?(String)
96
+ # Remote error text/data can include secrets; do not expose it via exceptions.
97
+ raise ProtocolError.new("Remote MCP protocol error (#{error['code']})", code: error["code"])
98
+ end
99
+ result = message["result"]
100
+ raise ProtocolError, "Invalid JSON-RPC result" if message.key?("error") || message.key?("method") || !result.is_a?(Hash)
101
+ raise ProtocolError, "Unknown MCP result type" unless %w[complete input_required].include?(result.fetch("resultType", "complete"))
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,69 @@
1
+ require "mcp"
2
+ require "mcp/client"
3
+ require "mcp/client/modern_envelope"
4
+ require "mcp/client/mcp_param_headers"
5
+ require "mcp/client/oauth/discovery"
6
+ require "mcp/client/oauth/pkce"
7
+ require "json_schemer"
8
+ require "event_stream_parser"
9
+ require "time"
10
+
11
+ module Connectors
12
+ module MCP
13
+ PROTOCOL_VERSION = "2026-07-28".freeze
14
+ class Error < Connectors::Error; end
15
+ class AccessDenied < Error; end
16
+ class ValidationError < Error; end
17
+ class ProtocolError < Error
18
+ attr_reader :code
19
+ def initialize(message, code: nil)
20
+ @code = code
21
+ super(message)
22
+ end
23
+ end
24
+ class TransportError < Error; end
25
+ class ConfigurationRequired < Error; end
26
+ class Cancelled < Error; end
27
+ class AuthorizationRequired < Error
28
+ attr_reader :challenge, :fingerprint
29
+ def initialize(challenge = {}, fingerprint: nil)
30
+ @challenge = challenge
31
+ @fingerprint = fingerprint
32
+ super("MCP owner authorization required")
33
+ end
34
+ end
35
+ class HTTPError < TransportError
36
+ attr_reader :status, :headers, :body
37
+ def initialize(status:, headers:, body:)
38
+ @status, @headers, @body = status, headers, body
39
+ super("Remote HTTP request failed (#{status})")
40
+ end
41
+
42
+ # Retry-After permits delay-seconds or an HTTP date. Do not reflect
43
+ # arbitrary upstream header content into host responses.
44
+ def retry_after
45
+ value = headers["retry-after"].to_s
46
+ return value if value.match?(/\A[0-9]+\z/)
47
+ Time.httpdate(value).httpdate
48
+ rescue ArgumentError
49
+ nil
50
+ end
51
+ end
52
+ end
53
+ end
54
+
55
+ require "connectors/mcp/settings"
56
+ require "connectors/mcp/cancellation"
57
+ require "connectors/mcp/access"
58
+ require "connectors/mcp/pending_transaction"
59
+ require "connectors/mcp/http"
60
+ require "connectors/mcp/connection_config"
61
+ require "connectors/mcp/authorization_discovery"
62
+ require "connectors/mcp/token_endpoint"
63
+ require "connectors/mcp/authorization"
64
+ require "connectors/mcp/authorization_context"
65
+ require "connectors/mcp/schema"
66
+ require "connectors/mcp/protocol_schema"
67
+ require "connectors/mcp/transport"
68
+ require "connectors/mcp/interaction"
69
+ require "connectors/mcp/client"
@@ -0,0 +1,79 @@
1
+ require "base64"
2
+
3
+ module Connectors
4
+ module Middleware
5
+ # Faraday middleware that applies a connector's declarative
6
+ # `authenticate type: :generic, properties: {...}` block to every
7
+ # outgoing request, mirroring n8n's `IAuthenticateGeneric` runtime
8
+ # (n8n source: packages/workflow/src/interfaces.ts:278-288 + the
9
+ # request-helpers consumer at
10
+ # packages/core/src/node-execute-functions.ts).
11
+ #
12
+ # The Grant's credentials hash supplies values for the
13
+ # `={{$credentials.x}}` templates inside `properties`. Resolution runs
14
+ # per-request so credentials that rotate between requests (e.g. after a
15
+ # `preAuthentication` hook lands in Phase 3) are reflected immediately.
16
+ class AuthenticateGeneric < Faraday::Middleware
17
+ def initialize(app, grant:, authenticate_config:)
18
+ super(app)
19
+ @grant = grant
20
+ @config = authenticate_config
21
+ end
22
+
23
+ def call(env)
24
+ properties = resolved_properties
25
+ apply_headers(env, properties[:headers] || properties["headers"])
26
+ apply_query(env, properties[:qs] || properties["qs"])
27
+ apply_body(env, properties[:body] || properties["body"])
28
+ apply_basic_auth(env, properties[:auth] || properties["auth"])
29
+
30
+ @app.call(env)
31
+ end
32
+
33
+ private
34
+
35
+ def resolved_properties
36
+ return {} if @config.nil?
37
+ AuthInjection.resolve(@config[:properties] || @config["properties"] || {}, @grant.credentials_hash)
38
+ end
39
+
40
+ def apply_headers(env, headers)
41
+ return if headers.nil? || headers.empty?
42
+ headers.each { |k, v| env.request_headers[k.to_s] = v.to_s }
43
+ end
44
+
45
+ def apply_query(env, qs)
46
+ return if qs.nil? || qs.empty?
47
+ # Faraday 2.x doesn't expose `env.params` reliably during middleware
48
+ # execution — the canonical mutation point is `env.url.query`. Merge
49
+ # with any existing query string so per-request params from the
50
+ # caller aren't clobbered.
51
+ existing = env.url.query ? URI.decode_www_form(env.url.query).to_h : {}
52
+ merged = existing.merge(qs.each_with_object({}) { |(k, v), h| h[k.to_s] = v.to_s })
53
+ env.url.query = URI.encode_www_form(merged)
54
+ end
55
+
56
+ # JSON-body injection only — most provider auth that sends creds in
57
+ # the body uses JSON. If a non-Hash body is in flight (form-encoded,
58
+ # multipart), leave it alone; Faraday's body coercion already ran by
59
+ # the time this middleware sees the env.
60
+ def apply_body(env, body)
61
+ return if body.nil? || body.empty?
62
+ return unless env.body.is_a?(Hash)
63
+ body.each { |k, v| env.body[k.to_s] = v }
64
+ end
65
+
66
+ # n8n's `IRequestOptionsSimplifiedAuth.auth` shortcut for HTTP Basic
67
+ # (interfaces.ts:198-202). Sets the `Authorization: Basic ...` header
68
+ # directly so we don't double-handle.
69
+ def apply_basic_auth(env, auth)
70
+ return if auth.nil?
71
+ username = auth[:username] || auth["username"]
72
+ password = auth[:password] || auth["password"]
73
+ return if username.nil? && password.nil?
74
+ encoded = Base64.strict_encode64("#{username}:#{password}")
75
+ env.request_headers["Authorization"] = "Basic #{encoded}"
76
+ end
77
+ end
78
+ end
79
+ end