new mcp servers format

This commit is contained in:
Davidson Gomes
2025-04-28 12:37:58 -03:00
parent 0112573d9b
commit e98744b7a4
7182 changed files with 4839 additions and 4998 deletions

View File

@@ -54,13 +54,12 @@ def BuildTopDescriptorsAndMessages(file_des, module_name, module):
module: Generated _pb2 module
"""
def BuildMessage(msg_des, prefix):
def BuildMessage(msg_des):
create_dict = {}
for (name, nested_msg) in msg_des.nested_types_by_name.items():
create_dict[name] = BuildMessage(nested_msg, prefix + msg_des.name + '.')
create_dict[name] = BuildMessage(nested_msg)
create_dict['DESCRIPTOR'] = msg_des
create_dict['__module__'] = module_name
create_dict['__qualname__'] = prefix + msg_des.name
message_class = _reflection.GeneratedProtocolMessageType(
msg_des.name, (_message.Message,), create_dict)
_sym_db.RegisterMessage(message_class)
@@ -84,7 +83,7 @@ def BuildTopDescriptorsAndMessages(file_des, module_name, module):
# Build messages.
for (name, msg_des) in file_des.message_types_by_name.items():
module[name] = BuildMessage(msg_des, '')
module[name] = BuildMessage(msg_des)
def AddHelpersToExtensions(file_des):

View File

@@ -412,13 +412,6 @@ class ScalarMap(MutableMapping[_K, _V]):
def __repr__(self) -> str:
return repr(self._values)
def setdefault(self, key: _K, value: Optional[_V] = None) -> _V:
if value == None:
raise ValueError('The value for scalar map setdefault must be set.')
if key not in self._values:
self.__setitem__(key, value)
return self[key]
def MergeFrom(self, other: 'ScalarMap[_K, _V]') -> None:
self._values.update(other._values)
self._message_listener.Modified()
@@ -533,12 +526,6 @@ class MessageMap(MutableMapping[_K, _V]):
def __repr__(self) -> str:
return repr(self._values)
def setdefault(self, key: _K, value: Optional[_V] = None) -> _V:
raise NotImplementedError(
'Set message map value directly is not supported, call'
' my_map[key].foo = 5'
)
def MergeFrom(self, other: 'MessageMap[_K, _V]') -> None:
# pylint: disable=protected-access
for key in other._values:

View File

@@ -58,7 +58,6 @@ we repeatedly read a tag, look up the corresponding decoder, and invoke it.
__author__ = 'kenton@google.com (Kenton Varda)'
import math
import numbers
import struct
from google.protobuf import message
@@ -72,27 +71,6 @@ from google.protobuf.internal import wire_format
_DecodeError = message.DecodeError
def IsDefaultScalarValue(value):
"""Returns whether or not a scalar value is the default value of its type.
Specifically, this should be used to determine presence of implicit-presence
fields, where we disallow custom defaults.
Args:
value: A scalar value to check.
Returns:
True if the value is equivalent to a default value, False otherwise.
"""
if isinstance(value, numbers.Number) and math.copysign(1.0, value) < 0:
# Special case for negative zero, where "truthiness" fails to give the right
# answer.
return False
# Normally, we can just use Python's boolean conversion.
return not value
def _VarintDecoder(mask, result_type):
"""Return an encoder for a basic varint value (does not include tag).
@@ -190,19 +168,6 @@ def ReadTag(buffer, pos):
return tag_bytes, pos
def DecodeTag(tag_bytes):
"""Decode a tag from the bytes.
Args:
tag_bytes: the bytes of the tag
Returns:
Tuple[int, int] of the tag field number and wire type.
"""
(tag, _) = _DecodeVarint(tag_bytes, 0)
return wire_format.UnpackTag(tag)
# --------------------------------------------------------------------
@@ -259,7 +224,7 @@ def _SimpleDecoder(wire_type, decode_value):
(new_value, pos) = decode_value(buffer, pos)
if pos > end:
raise _DecodeError('Truncated message.')
if clear_if_default and IsDefaultScalarValue(new_value):
if clear_if_default and not new_value:
field_dict.pop(key, None)
else:
field_dict[key] = new_value
@@ -500,7 +465,7 @@ def EnumDecoder(field_number, is_repeated, is_packed, key, new_default,
(enum_value, pos) = _DecodeSignedVarint32(buffer, pos)
if pos > end:
raise _DecodeError('Truncated message.')
if clear_if_default and IsDefaultScalarValue(enum_value):
if clear_if_default and not enum_value:
field_dict.pop(key, None)
return pos
# pylint: disable=protected-access
@@ -595,7 +560,7 @@ def StringDecoder(field_number, is_repeated, is_packed, key, new_default,
new_pos = pos + size
if new_pos > end:
raise _DecodeError('Truncated string.')
if clear_if_default and IsDefaultScalarValue(size):
if clear_if_default and not size:
field_dict.pop(key, None)
else:
field_dict[key] = _ConvertToUnicode(buffer[pos:new_pos])
@@ -636,7 +601,7 @@ def BytesDecoder(field_number, is_repeated, is_packed, key, new_default,
new_pos = pos + size
if new_pos > end:
raise _DecodeError('Truncated string.')
if clear_if_default and IsDefaultScalarValue(size):
if clear_if_default and not size:
field_dict.pop(key, None)
else:
field_dict[key] = buffer[pos:new_pos].tobytes()
@@ -765,6 +730,7 @@ def MessageSetItemDecoder(descriptor):
local_ReadTag = ReadTag
local_DecodeVarint = _DecodeVarint
local_SkipField = SkipField
def DecodeItem(buffer, pos, end, message, field_dict):
"""Decode serialized message set to its value and new position.
@@ -796,10 +762,9 @@ def MessageSetItemDecoder(descriptor):
elif tag_bytes == item_end_tag_bytes:
break
else:
field_number, wire_type = DecodeTag(tag_bytes)
_, pos = _DecodeUnknownField(buffer, pos, end, field_number, wire_type)
pos = SkipField(buffer, pos, end, tag_bytes)
if pos == -1:
raise _DecodeError('Unexpected end-group tag.')
raise _DecodeError('Missing group end tag.')
if pos > end:
raise _DecodeError('Truncated message.')
@@ -857,10 +822,9 @@ def UnknownMessageSetItemDecoder():
elif tag_bytes == item_end_tag_bytes:
break
else:
field_number, wire_type = DecodeTag(tag_bytes)
_, pos = _DecodeUnknownField(buffer, pos, end, field_number, wire_type)
pos = SkipField(buffer, pos, end, tag_bytes)
if pos == -1:
raise _DecodeError('Unexpected end-group tag.')
raise _DecodeError('Missing group end tag.')
if pos > end:
raise _DecodeError('Truncated message.')
@@ -918,6 +882,30 @@ def MapDecoder(field_descriptor, new_default, is_message_map):
return DecodeMap
# --------------------------------------------------------------------
# Optimization is not as heavy here because calls to SkipField() are rare,
# except for handling end-group tags.
def _SkipVarint(buffer, pos, end):
"""Skip a varint value. Returns the new position."""
# Previously ord(buffer[pos]) raised IndexError when pos is out of range.
# With this code, ord(b'') raises TypeError. Both are handled in
# python_message.py to generate a 'Truncated message' error.
while ord(buffer[pos:pos+1].tobytes()) & 0x80:
pos += 1
pos += 1
if pos > end:
raise _DecodeError('Truncated message.')
return pos
def _SkipFixed64(buffer, pos, end):
"""Skip a fixed64 value. Returns the new position."""
pos += 8
if pos > end:
raise _DecodeError('Truncated message.')
return pos
def _DecodeFixed64(buffer, pos):
"""Decode a fixed64."""
@@ -925,11 +913,25 @@ def _DecodeFixed64(buffer, pos):
return (struct.unpack('<Q', buffer[pos:new_pos])[0], new_pos)
def _DecodeFixed32(buffer, pos):
"""Decode a fixed32."""
def _SkipLengthDelimited(buffer, pos, end):
"""Skip a length-delimited value. Returns the new position."""
new_pos = pos + 4
return (struct.unpack('<I', buffer[pos:new_pos])[0], new_pos)
(size, pos) = _DecodeVarint(buffer, pos)
pos += size
if pos > end:
raise _DecodeError('Truncated message.')
return pos
def _SkipGroup(buffer, pos, end):
"""Skip sub-group. Returns the new position."""
while 1:
(tag_bytes, pos) = ReadTag(buffer, pos)
new_pos = SkipField(buffer, pos, end, tag_bytes)
if new_pos == -1:
return pos
pos = new_pos
def _DecodeUnknownFieldSet(buffer, pos, end_pos=None):
@@ -942,16 +944,14 @@ def _DecodeUnknownFieldSet(buffer, pos, end_pos=None):
field_number, wire_type = wire_format.UnpackTag(tag)
if wire_type == wire_format.WIRETYPE_END_GROUP:
break
(data, pos) = _DecodeUnknownField(
buffer, pos, end_pos, field_number, wire_type
)
(data, pos) = _DecodeUnknownField(buffer, pos, wire_type)
# pylint: disable=protected-access
unknown_field_set._add(field_number, wire_type, data)
return (unknown_field_set, pos)
def _DecodeUnknownField(buffer, pos, end_pos, field_number, wire_type):
def _DecodeUnknownField(buffer, pos, wire_type):
"""Decode a unknown field. Returns the UnknownField and new position."""
if wire_type == wire_format.WIRETYPE_VARINT:
@@ -965,19 +965,72 @@ def _DecodeUnknownField(buffer, pos, end_pos, field_number, wire_type):
data = buffer[pos:pos+size].tobytes()
pos += size
elif wire_type == wire_format.WIRETYPE_START_GROUP:
end_tag_bytes = encoder.TagBytes(
field_number, wire_format.WIRETYPE_END_GROUP
)
data, pos = _DecodeUnknownFieldSet(buffer, pos, end_pos)
# Check end tag.
if buffer[pos - len(end_tag_bytes) : pos] != end_tag_bytes:
raise _DecodeError('Missing group end tag.')
(data, pos) = _DecodeUnknownFieldSet(buffer, pos)
elif wire_type == wire_format.WIRETYPE_END_GROUP:
return (0, -1)
else:
raise _DecodeError('Wrong wire type in tag.')
if pos > end_pos:
raise _DecodeError('Truncated message.')
return (data, pos)
def _EndGroup(buffer, pos, end):
"""Skipping an END_GROUP tag returns -1 to tell the parent loop to break."""
return -1
def _SkipFixed32(buffer, pos, end):
"""Skip a fixed32 value. Returns the new position."""
pos += 4
if pos > end:
raise _DecodeError('Truncated message.')
return pos
def _DecodeFixed32(buffer, pos):
"""Decode a fixed32."""
new_pos = pos + 4
return (struct.unpack('<I', buffer[pos:new_pos])[0], new_pos)
def _RaiseInvalidWireType(buffer, pos, end):
"""Skip function for unknown wire types. Raises an exception."""
raise _DecodeError('Tag had invalid wire type.')
def _FieldSkipper():
"""Constructs the SkipField function."""
WIRETYPE_TO_SKIPPER = [
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
]
wiretype_mask = wire_format.TAG_TYPE_MASK
def SkipField(buffer, pos, end, tag_bytes):
"""Skips a field with the specified tag.
|pos| should point to the byte immediately after the tag.
Returns:
The new position (after the tag value), or -1 if the tag is an end-group
tag (in which case the calling loop should break).
"""
# The wire type is always in the first byte since varints are little-endian.
wire_type = ord(tag_bytes[0:1]) & wiretype_mask
return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)
return SkipField
SkipField = _FieldSkipper()

View File

View File

@@ -2,4 +2,4 @@
This file contains the serialized FeatureSetDefaults object corresponding to
the Pure Python runtime. This is used for feature resolution under Editions.
"""
_PROTOBUF_INTERNAL_PYTHON_EDITION_DEFAULTS = b"\n\025\030\204\007\"\000*\016\010\001\020\002\030\002 \003(\0010\0028\002\n\025\030\347\007\"\000*\016\010\002\020\001\030\001 \002(\0010\0018\002\n\025\030\350\007\"\014\010\001\020\001\030\001 \002(\0010\001*\0028\002 \346\007(\350\007"
_PROTOBUF_INTERNAL_PYTHON_EDITION_DEFAULTS = b"\n\023\030\204\007\"\000*\014\010\001\020\002\030\002 \003(\0010\002\n\023\030\347\007\"\000*\014\010\002\020\001\030\001 \002(\0010\001\n\023\030\350\007\"\014\010\001\020\001\030\001 \002(\0010\001*\000 \346\007(\350\007"

View File

@@ -29,7 +29,6 @@ __author__ = 'robinson@google.com (Will Robinson)'
import datetime
from io import BytesIO
import math
import struct
import sys
import warnings
@@ -523,11 +522,7 @@ def _AddInitMethod(message_descriptor, cls):
if _IsMapField(field):
if _IsMessageMapField(field):
for key in field_value:
item_value = field_value[key]
if isinstance(item_value, dict):
field_copy[key].__init__(**item_value)
else:
field_copy[key].MergeFrom(item_value)
field_copy[key].MergeFrom(field_value[key])
else:
field_copy.update(field_value)
else:
@@ -721,14 +716,14 @@ def _AddPropertiesForNonRepeatedScalarField(field, cls):
def field_setter(self, new_value):
# pylint: disable=protected-access
# Testing the value for truthiness captures all of the implicit presence
# defaults (0, 0.0, enum 0, and False), except for -0.0.
# Testing the value for truthiness captures all of the proto3 defaults
# (0, 0.0, enum 0, and False).
try:
new_value = type_checker.CheckValue(new_value)
except TypeError as e:
raise TypeError(
'Cannot set %s to %.1024r: %s' % (field.full_name, new_value, e))
if not field.has_presence and decoder.IsDefaultScalarValue(new_value):
if not field.has_presence and not new_value:
self._fields.pop(field, None)
else:
self._fields[field] = new_value
@@ -1197,6 +1192,8 @@ def _AddMergeFromStringMethod(message_descriptor, cls):
return length # Return this for legacy reasons.
cls.MergeFromString = MergeFromString
local_ReadTag = decoder.ReadTag
local_SkipField = decoder.SkipField
fields_by_tag = cls._fields_by_tag
message_set_decoders_by_tag = cls._message_set_decoders_by_tag
@@ -1218,7 +1215,7 @@ def _AddMergeFromStringMethod(message_descriptor, cls):
self._Modified()
field_dict = self._fields
while pos != end:
(tag_bytes, new_pos) = decoder.ReadTag(buffer, pos)
(tag_bytes, new_pos) = local_ReadTag(buffer, pos)
field_decoder, field_des = message_set_decoders_by_tag.get(
tag_bytes, (None, None)
)
@@ -1229,17 +1226,23 @@ def _AddMergeFromStringMethod(message_descriptor, cls):
if field_des is None:
if not self._unknown_fields: # pylint: disable=protected-access
self._unknown_fields = [] # pylint: disable=protected-access
field_number, wire_type = decoder.DecodeTag(tag_bytes)
# pylint: disable=protected-access
(tag, _) = decoder._DecodeVarint(tag_bytes, 0)
field_number, wire_type = wire_format.UnpackTag(tag)
if field_number == 0:
raise message_mod.DecodeError('Field number 0 is illegal.')
# TODO: remove old_pos.
old_pos = new_pos
(data, new_pos) = decoder._DecodeUnknownField(
buffer, new_pos, end, field_number, wire_type
) # pylint: disable=protected-access
buffer, new_pos, wire_type) # pylint: disable=protected-access
if new_pos == -1:
return pos
# TODO: remove _unknown_fields.
new_pos = local_SkipField(buffer, old_pos, end, tag_bytes)
if new_pos == -1:
return pos
self._unknown_fields.append(
(tag_bytes, buffer[pos + len(tag_bytes) : new_pos].tobytes())
)
(tag_bytes, buffer[old_pos:new_pos].tobytes()))
pos = new_pos
else:
_MaybeAddDecoder(cls, field_des)

View File

@@ -37,9 +37,6 @@ class LocalTestResult(unittest.TestResult):
def addSkip(self, test, reason):
pass
def addDuration(self, test, duration):
pass
class ReferenceLeakCheckerMixin(object):
"""A mixin class for TestCase, which checks reference counts."""
@@ -62,7 +59,7 @@ class ReferenceLeakCheckerMixin(object):
super(ReferenceLeakCheckerMixin, self).run(result=result)
super(ReferenceLeakCheckerMixin, self).run(result=result)
oldrefcount = 0 # pylint: disable=unused-variable but needed for refcounts.
oldrefcount = 0
local_result = LocalTestResult(result)
num_flakes = 0

View File

@@ -231,7 +231,6 @@ class Uint64ValueChecker(IntValueChecker):
# The max 4 bytes float is about 3.4028234663852886e+38
_FLOAT_MAX = float.fromhex('0x1.fffffep+127')
_FLOAT_MIN = -_FLOAT_MAX
_MAX_FLOAT_AS_DOUBLE_ROUNDED = 3.4028235677973366e38
_INF = float('inf')
_NEG_INF = float('-inf')
@@ -270,12 +269,8 @@ class FloatValueChecker(DoubleValueChecker):
converted_value = super().CheckValue(proposed_value)
# This inf rounding matches the C++ proto SafeDoubleToFloat logic.
if converted_value > _FLOAT_MAX:
if converted_value <= _MAX_FLOAT_AS_DOUBLE_ROUNDED:
return _FLOAT_MAX
return _INF
if converted_value < _FLOAT_MIN:
if converted_value >= -_MAX_FLOAT_AS_DOUBLE_ROUNDED:
return _FLOAT_MIN
return _NEG_INF
return TruncateToFourByteFloat(converted_value)

View File

@@ -26,7 +26,7 @@ from typing import Union
FieldMask = field_mask.FieldMask
_TIMESTAMPFORMAT = '%Y-%m-%dT%H:%M:%S'
_TIMESTAMPFOMAT = '%Y-%m-%dT%H:%M:%S'
_NANOS_PER_SECOND = 1000000000
_NANOS_PER_MILLISECOND = 1000000
_NANOS_PER_MICROSECOND = 1000
@@ -68,7 +68,7 @@ class Any(object):
def TypeName(self):
"""Returns the protobuf type name of the inner message."""
# Only last part is to be used: b/25630112
return self.type_url.rpartition('/')[2]
return self.type_url.split('/')[-1]
def Is(self, descriptor):
"""Checks if this Any represents the given protobuf type."""
@@ -142,7 +142,7 @@ class Timestamp(object):
raise ValueError(
'time data \'{0}\' does not match format \'%Y-%m-%dT%H:%M:%S\', '
'lowercase \'t\' is not accepted'.format(second_value))
date_object = datetime.datetime.strptime(second_value, _TIMESTAMPFORMAT)
date_object = datetime.datetime.strptime(second_value, _TIMESTAMPFOMAT)
td = date_object - datetime.datetime(1970, 1, 1)
seconds = td.seconds + td.days * _SECONDS_PER_DAY
if len(nano_value) > 9: